0%

Gin web framework

Gin 是一个用 Go (Golang) 编写的 HTTP web 框架。 它是一个类似于 martini 但拥有更好性能的 API 框架, 由于 httprouter,速度提高了近 40 倍。如果你需要极好的性能,使用 Gin 吧。

官方文档

https://gin-gonic.com/docs/

安装

1
go get -u github.com/gin-gonic/gin

example(API)

GitHub 代码

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main

import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"strings"
"time"
)

func CORS() gin.HandlerFunc {
return func(context *gin.Context) {
context.Writer.Header().Add("Access-Control-Allow-Origin", context.Request.Header.Get("Origin"))
context.Writer.Header().Set("Access-Control-Max-Age", "86400")
context.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH")
context.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Apitoken")
context.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

if context.Request.Method == "OPTIONS" {
context.AbortWithStatus(http.StatusOK)
} else {
context.Next()
}
}
}

func AuthSessionMiddle(context *gin.Context) {
token := context.Request.Header.Get("token")
if token == "test-token" {
context.Set("auth", true)
context.Next()
} else {
context.Set("auth", false)
context.AbortWithStatus(http.StatusUnauthorized)
}
}

// url上的参数
type APITestQueryInputs struct {
Limit int `json:"limit" form:"limit"`
Page int `json:"page" form:"page"`
}

func GetTest(context *gin.Context) {
// 默认值
inputs := APITestQueryInputs{
Limit: 500,
Page: 1,
}
if err := context.Bind(&inputs); err != nil {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": err.Error()})
return
}
// do something
fmt.Printf("do something\n")
context.JSON(http.StatusOK, gin.H{"status": "ok"})
}

type APITestReqData struct {
Name string `json:"name" binding:"required"`
Tests []string `json:"tests" binding:"required"`
Count int `json:"count" binding:"required"`
CreateTime *time.Time `json:"create_time"`
UpdateTime *time.Time `json:"update_time"`
}

func (a APITestReqData) CheckFormat() (err error) {
switch {
case !strings.HasPrefix(a.Name, "test"):
err = errors.New("name do not start with 'test'")
case a.Count > 10:
err = errors.New("'count' cannot greater than 10")
}
return
}

func PostTest(context *gin.Context) {
var inputs APITestReqData
if err := context.Bind(&inputs); err != nil {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": err.Error()})
return
}

// 检查入参
err := inputs.CheckFormat()
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": err.Error()})
return
}

// do something
fmt.Printf("do something\n")

context.JSON(http.StatusOK, gin.H{"status": "ok"})
}

func PutTest(context *gin.Context) {
id := context.Param("id")
idInt, err := strconv.Atoi(id)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": err.Error()})
}
if idInt <= 0 {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": "illegal parameter"})
}
// do something
fmt.Printf("do something\n")
context.JSON(http.StatusOK, gin.H{"status": "ok"})
}

func DeleteTest(context *gin.Context) {
id := context.Param("id")
idInt, err := strconv.Atoi(id)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": err.Error()})
}
if idInt <= 0 {
context.JSON(http.StatusBadRequest, gin.H{"status": "error", "msg": "illegal parameter"})
}
// do something
fmt.Printf("do something\n")
context.JSON(http.StatusOK, gin.H{"status": "ok"})
}

func GenerateRoutes(r *gin.Engine) {
api := r.Group("/api/v1")
api.Use(AuthSessionMiddle)

// curl -H Content-Type:application/json -H token:test-token http://127.0.0.1:8080/api/v1/test
api.GET("/test", GetTest)

// curl -X POST -H Content-Type:application/json -H token:test-token -d '{"name":"test-1111","tests":["111","222"],"count":10,"create_time":"2019-12-25T10:10:10Z","update_time":"2019-12-25T10:10:11Z"}' http://127.0.0.1:8080/api/v1/test
api.POST("/test", PostTest)

// curl -X PUT -H Content-Type:application/json -H token:test-token http://127.0.0.1:8080/api/v1/test/1
api.PUT("/test/:id", PutTest)

// curl -X DELETE -H Content-Type:application/json -H token:test-token http://127.0.0.1:8080/api/v1/test/1
api.DELETE("/test/:id", DeleteTest)
}

func main() {
r := gin.Default()
r.Use(CORS())

// string
// curl http://127.0.0.1:8080
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello, I'm Gin\n")
})

// json
// curl http://127.0.0.1:8080/json
r.GET("/json", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, I'm Gin"})
})

GenerateRoutes(r)

_ = r.Run(":8080") //默认端口是8080
}

grinning all the time

😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄