Gin是一个使用 Go 语言开发的 Web 框架,它提供类似 Martini 的 API,但性能更佳,速度提升高达 40 倍(基于 httprouter 实现)。
介绍
开发
- Golang 开发中的热加载工具
- Swagger
- gin 运行的三种模式,参考
DebugMode
默认模式,比 ReleaseMode
多了一些额外的错误信息
ReleaseMode
发布模式优化调试输出,如路由日志不会输出到终端
TestMode
- 设置方式
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
vscode 自动加载?
组成
示例
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 默认路由引擎
r := gin.Default()
// 路由配置
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// 启动 HTTP 服务
//r.Run("0.0.0.0:8000")
//r.Run(":8000")
_ = r.Run()
// curl http://127.0.0.1:8080/ping
//{"message":"pong"}
}
session
集成 swag
go install github.com/swaggo/swag/cmd/swag@latest
# help
swag -h
swag init -h
swag fmt -h
# 默认指定 main.go 文件
swag init
# 手动指定文件
swag init -g http/api.go
# 自动格式化 swag 格式文件
swag fmt
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
// GetStringByInt example
//
// @Deprecated
// @Summary Add a new pet to the store
// @Description get string by ID
// @ID get-string-by-int
// @Accept json
// @Produce json
// @Param some_id path int true "Some ID"
// @Param some_id body web.Pet true "Some ID"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]
// GetUser example
//
// @Summary Read user from the store
// @Tags admin
// @Accept json
// @Produce json
// @Param id path int true "User Id"
// @Success 200 {object} api.User
// @Failure 400 {object} api.APIError "We need ID!!"
// @Failure 404 {object} api.APIError "Can not find ID"
// @Router /admin/user/{id} [get]
func GetUser(w http.ResponseWriter, r *http.Request) {
// write your code
}
// Deprecated: xxx
func ...
集成 validator
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type User struct {
Username string `validate:"min=5,max=16"`
Age uint8 `validate:"gte=1,lte=10"`
Sex string `validate:"oneof=female male"`
}
func main() {
validate := validator.New()
user1 := User{Username: "xianbin", Age: 18, Sex: "null"}
err := validate.Struct(user1)
if err != nil {
fmt.Println(err)
}
user2 := User{Username: "xianbin888", Age: 18, Sex: "male"}
err = validate.Struct(user2)
if err != nil {
fmt.Println(err)
}
}
- 字符串约束
excludesall
不包含参数中任意的 UNICODE 字符,例如 excludesall=xianbin
excludesrune
不包含参数表示的 rune 字符,例如 excludesrune=xianbin
startswith
以参数子串为前缀,例如 startswith=hi
endswith
以参数子串为后缀,例如 endswith=bye
contains=
包含参数子串,例如 contains=email
containsany
包含参数中任意的 UNICODE 字符,例如 containsany=xianbin
containsrune
包含参数表示的 rune 字符,例如 containsrune=xianbin
excludes
不包含参数子串,例如 excludes=email
- 常用 tag 介绍
ne
不等于参数值,例如 ne=5
gt
大于参数值,例如 gt=5
gte
大于等于参数值,例如 gte=50
lt
小于参数值,例如 lt=50
lte
小于等于参数值,例如 lte=50
oneof
只能是列举出的值其中一个,这些值必须是数值或字符串,以空格分隔,如果字符串中有空格,将字符串用单引号包围,例如 oneof=male female
eq
等于参数值,注意与 len 不同。对于字符串,eq 约束字符串本身的值,而 len 约束字符串长度,例如 eq=10
len
等于参数值,例如 len=10
max
小于等于参数值,例如 max=10
min
大于等于参数值,例如 min=10
- Fields 约束
eqfield
定义字段间的相等约束,用于约束同一结构体中的字段,例如 eqfield=Password
eqcsfield
约束统一结构体中字段等于另一个字段(相对),确认密码时可以使用,例如 eqfiel=ConfirmPassword
nefield
用来约束两个字段是否相同,确认两种颜色是否一致时可以使用,例如 nefield=Color1
necsfield
约束两个字段是否相同(相对)
- 常用约束
unique
指定唯一性约束,不同类型处理不同
- 对于
map,unique
约束没有重复的值
- 对于数组和切片,
unique
没有重复的值
- 对于元素类型为结构体的碎片,
unique
约束结构体对象的某个字段不重复,使用unique=field
指定字段名
email
邮件格式,无需加任何指定
omitempty
字段未设置,则忽略
-
跳过该字段,不检验
|
使用多个约束,只需要满足其中一个,例如 rgb|rgba
required
字段必须设置,不能为默认值
其他