Gin
Web框架,封装比较优雅,API友好。具有快速灵活,容错方便等特点
安装
1
| go get -u github.com/gin-gonic/gin
|
hello world
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package main
import "github.com/gin-gonic/gin"
func main() { ginServer := gin.Default()
ginServer.GET("/hello", func(context *gin.Context) { context.JSON(200, gin.H{"msg": "hello"}) })
err := ginServer.Run(":8082") if err != nil { return }
}
|
响应页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| func main() { ginServer := gin.Default()
ginServer.LoadHTMLGlob("templates/*")
ginServer.GET("/index", func(context *gin.Context) { context.HTML(http.StatusOK, "index.html", gin.H{"msg": "你好"}) })
err := ginServer.Run(":8082") if err != nil { return }
}
|
获取请求参数
路径参数c.Param()
1 2 3 4 5 6 7
| r.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") action = strings.Trim(action, "/") c.String(http.StatusOK, name+" is "+action) })
|
URL参数c.Query()/DefaultQuery()
1 2 3 4 5 6
| r.GET("/user", func(c *gin.Context) { name := c.DefaultQuery("name", "枯藤") c.String(http.StatusOK, fmt.Sprintf("hello %s", name)) })
|
表单参数c.PostForm()/DefaultPostForm()
表单格式常见有:
- application/json json格式
- application/x-www-form-urlencoded 表单
- application/xml xml
- multipart/form-data 文件
文件c.FormFile()
1 2 3 4 5 6 7 8 9 10 11
| r.MaxMultipartMemory = 8 << 20 r.POST("/upload", func(c *gin.Context) { file, err := c.FormFile("file") if err != nil { c.String(500, "上传图片出错") } c.SaveUploadedFile(file, file.Filename) c.String(http.StatusOK, file.Filename) })
|
提取请求路径的公共头部分
1 2 3 4 5 6 7 8
| v1 := r.Group("/v1")
{ v1.GET("/login", login) v1.GET("submit", submit) }
|