一.安装 git
使用go下载gin库,命令行输入:go get github.com/gin-gonic/gin
,通常使用须要的依赖:github
import "github.com/gin-gonic/gin" import "net/http"
二:基本应用浏览器
1. GET
1)gin.Context中的Query方法:get的URL传参测试
二:基本应用命令行
1. GET
1)gin.Context中的Query方法:get的URL传参code
package main import ( "github.com/gin-gonic/gin" "net/http" ) func getQuery(context *gin.Context){ userid := context.Query("userid") username := context.Query("username") context.String(http.StatusOK,userid+" "+username) } func main(){ // 注册一个默认路由器 router := gin.Default() //注册GET处理 router.GET("/user", getQuery) //默认8080端口 router.Run(":8088") }
测试:URL:http://localhost:8088/user?userid=5&username=xiaoming
浏览器输出:5 xiaomingrouter
2.gin.Context中的Param方法:RESRful风格URL传参blog
package main import ( "github.com/gin-gonic/gin" "net/http" ) func getParam(context *gin.Context){ userid := context.Param("userid") username := context.Param("username") context.String(http.StatusOK,userid+" "+username) } func main(){ // 注册一个默认路由器 router := gin.Default() //注册GET处理 //router.GET("/user", getQuery) router.GET("/user/:userid/:username",getParam) //默认8080端口 router.Run(":8088") }
补充:/:varname必须匹配对应的,/*varname匹配后面的全部,同时不能用多个,不然编译报错
测试:URL:http://localhost:8088/user/5/xiaoming
页面输出:5 xiaoming路由