Gin

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()

// 访问地址
// gin.Context,封装了request和response
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()

// 在项目目录下创建文件夹templates及页面index.html
// 加载静态页面
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) {
//DefaultQuery指定默认值
//http://localhost:8080/user 才会打印出来默认的值
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.JSON(200, gin.H{"message": file.Header.Context})
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)
}

// 请求路径/v1/login

Gin
http://xwww12.github.io/2023/10/22/go/Gin/
作者
xw
发布于
2023年10月22日
许可协议