Gin 框架学习【第一篇】

安装Gin

go get -u -v github.com/gin-gonic/gin 下载依赖,也可以在 mod 模式的项目中倒入依赖。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
"github.com/gin-gonic/gin"
"net/http"
)

func main() {
engine.GET("/people", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"responseCode": "0000",
"responseMsg": "成功",
"method": "GET",
})
})
engine.POST("/people", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"responseCode": "0000",
"responseMsg": "成功",
"method": "POST",
})
})
engine.PUT("/people", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"responseCode": "0000",
"responseMsg": "成功",
"method": "PUT",
})
})
engine.DELETE("/people", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"responseCode": "0000",
"responseMsg": "成功",
"method": "DELETE",
})
})

engine.Run(":9090")
}
//可以使用 postman 进行上述请求的测试

这里和原生的 Go web 代码主要差别是在。handler 函数的参数重,gin.Context 代替了原来的 http.ResponseWriterhttp.Requesthttp.ListenAndServegin.Run 代替。