1.安装并引入
$ go get -u github.com/gin-gonic/gin
import "github.com/gin-gonic/gin"
2.创建服务
//创建服务 ginServer := gin.Default() //处理请求 ginServer.GET("/hello", func(context *gin.Context) { context.JSON(200, gin.H{"msg": "hello"}) }) //指定服务器端口 ginServer.Run(":8082")
3.加载静态资源并访问页面
// 加载静态页面 ginServer.LoadHTMLGlob("templates/*") //响应页面 ginServer.GET("index", func(context *gin.Context) { context.HTML(http.StatusOK, "index.html", gin.H{ "msg": "hello", }) })
4.加载资源文件并访问页面
//加载资源文件 ginServer.Static("static", "./static") ginServer.GET("index", func(context *gin.Context) { context.HTML(http.StatusOK, "index.html", gin.H{ "msg": "hello", }) })
5.传递参数
ginServer.GET("usr/info", func(context *gin.Context) { userid := context.Query("userid") username := context.Query("username") context.HTML(http.StatusOK, "index.html", gin.H{ "userid": userid, "username": username, }) })
6.restful传递参数
//localhost:8082/user/info/100/user ginServer.GET("user/info/:userid/:username", func(context *gin.Context) { userid := context.Param("userid") username := context.Param("username") context.HTML(http.StatusOK, "index.html", gin.H{ "userid": userid, "username": username, }) })
7.接收并返回json
ginServer.POST("/json", func(context *gin.Context) { // request.body data, _ := context.GetRawData() var m map[string]interface{} json.Unmarshal(data, &m) context.JSON(http.StatusOK, m) })
8.表单提交
ginServer.POST("/user/add", func(context *gin.Context) { username := context.PostForm("username") pwd := context.PostForm("pwd") context.JSON(http.StatusOK, gin.H{ "username": username, "userpwd": pwd, }) })
9.重定向和404
// 重定向 ginServer.GET("/redirect", func(context *gin.Context) { context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com") }) // 404 ginServer.NoRoute(func(context *gin.Context) { context.HTML(http.StatusNotFound, "404.html", nil) })
10.中间件
func myHandler() gin.HandlerFunc { return func(ctx *gin.Context) { ctx.Set("userSession", "userid-1") ctx.Next() //放行 //ctx.Abort()//阻止 } }