Gin 基础
admin
2024-04-02 16:40:53
0

官网
Gin是一个用Go (Golang)编写的HTTP web框架。它的特点是一个类似Martini-like API,由于使用了httprouter,它的性能提高了40倍。如果您需要性能和良好的生产力,您将爱上Gin。

Martini 是 Go 生态中的一个 Web 框架:
Martini-like API 是指 Gin 框架内部的 API 命名风格、传参形式跟 Martini 类似。比如定义一个路由分组:

// Martini
m.Group("/users", func(r martini.Router) {r.Post("/", CreateUserEndpoint)r.Get("/:id", GetUserEndpoint)r.Put("/:id", UpdateUserEndpoint)r.Delete("/:id", DeleteUserEndpoint)
})// Gin
r := engine.Group("/users") {r.POST("/", CreateUserEndpoint)r.GET("/:id", GetUserEndpoint)r.PUT("/:id", UpdateUserEndpoint)r.DELETE("/:id", DeleteUserEndpoint)
}

因为 Martini 诞生的比较早(2013 年),所以作为 2015 年才出现的“后辈” Gin 来说保持一个跟当时比较流行的框架一样的 API,比较容易吸引人们去学习和理解、也降低了开发者们现有项目的迁移成本。

一、Gin v1. stable

1.1 特点:

1、零配置路由器
2、仍然是最快的http路由器和框架。从路由到写入。
3、完整的单元测试套件。
4、Battle tested
5、API被冻结,新版本不会破坏你的代码。

1.2 Build with jsoniter

jsoniter

一个对“encoding/json” 100%兼容的高性能插拔的替换

Gin使用 encoding/json 作为默认的json包,但你可以通过从其他标签构建来更改为 jsoniter。

go build -tags=jsoniter .

go-json

go build -tags=go_json .

sonic

you have to ensure that your cpu support avx instruction

go build -tags="sonic avx" .

构建时不使用MsgPack渲染功能

Gin默认启用MsgPack渲染功能。但是可以通过指定nomsgpack构建标记禁用此功能。

go build -tags=nomsgpack .

这有助于减少可执行文件的二进制大小

1.4 部署

Gin项目可以轻松地部署在任何云提供商上。

1.5 测试

如何为Gin写测试用例?
net/http/httptest是HTTP测试的首选方法。

// example.go
package mainimport "github.com/gin-gonic/gin"func setupRouter() *gin.Engine {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.String(200, "pong")})return r
}func main() {r := setupRouter()r.Run(":8080")
}

测试上面的代码示例:

// example_test.go
package mainimport ("net/http""net/http/httptest""testing""github.com/stretchr/testify/assert"
)func TestPingRoute(t *testing.T) {router := setupRouter()w := httptest.NewRecorder()req, _ := http.NewRequest("GET", "/ping", nil)router.ServeHTTP(w, req)assert.Equal(t, 200, w.Code)assert.Equal(t, "pong", w.Body.String())
}

二、API

Engine

type Engine struct {
}

gin.Default() 返回一个已经附加了 LoggerRecovery 中间件的引擎实例(Engine)。

// ServeHTTP遵循 http.Handler 接口
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

Context

type Context struct {writermem responseWriterRequest   *http.RequestWriter    ResponseWriterParams   Paramshandlers HandlersChainindex    int8fullPath stringengine       *Engineparams       *ParamsskippedNodes *[]skippedNode// This mutex protects Keys map.mu sync.RWMutex// Keys is a key/value pair exclusively for the context of each request.Keys map[string]any// Errors is a list of errors attached to all the handlers/middlewares who used this context.Errors errorMsgs// Accepted defines a list of manually accepted formats for content negotiation.Accepted []string// queryCache caches the query result from c.Request.URL.Query().queryCache url.Values// formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH,// or PUT body parameters.formCache url.Values// SameSite allows a server to define a cookie attribute making it impossible for// the browser to send this cookie along with cross-site requests.sameSite http.SameSite
}

2.1 Using GET, POST, PUT, PATCH, DELETE and OPTIONS

func main() {// Creates a gin router with default middleware:// logger and recovery (crash-free) middlewarerouter := gin.Default()router.GET("/someGet", getting)router.POST("/somePost", posting)router.PUT("/somePut", putting)router.DELETE("/someDelete", deleting)router.PATCH("/somePatch", patching)router.HEAD("/someHead", head)router.OPTIONS("/someOptions", options)// By default it serves on :8080 unless a// PORT environment variable was defined.router.Run()// router.Run(":3000") for a hard coded port
}

RouterGroup

func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes// HandlerFunc defines the handler used by gin middleware as return value.
type HandlerFunc func(*Context)

2.2 路径参数

func main() {router := gin.Default()// This handler will match /user/john but will not match /user/ or /userrouter.GET("/user/:name", func(c *gin.Context) {name := c.Param("name")c.String(http.StatusOK, "Hello %s", name)})// However, this one will match /user/john/ and also /user/john/send// If no other routers match /user/john, it will redirect to /user/john/router.GET("/user/:name/*action", func(c *gin.Context) {name := c.Param("name")action := c.Param("action")message := name + " is " + actionc.String(http.StatusOK, message)})// For each matched request Context will hold the route definitionrouter.POST("/user/:name/*action", func(c *gin.Context) {b := c.FullPath() == "/user/:name/*action" // truec.String(http.StatusOK, "%t", b)})// This handler will add a new router for /user/groups.// Exact routes are resolved before param routes, regardless of the order they were defined.// Routes starting with /user/groups are never interpreted as /user/:name/... routesrouter.GET("/user/groups", func(c *gin.Context) {c.String(http.StatusOK, "The available groups are [...]")})router.Run(":8080")
}

相关内容

热门资讯

安卓系统所有手机通用,揭秘所有... 你有没有发现,现在市面上各种各样的手机,品牌琳琅满目,让人挑花了眼?不过,不管你用的是哪个品牌的手机...
安卓系统变ios系统好用吗,体... 你有没有想过,为什么有些人从安卓手机换到了苹果的iPhone,而且好像换了之后整个人都精神焕发呢?没...
华为安卓系统文件删除,轻松掌握... 你有没有遇到过这种情况?手机里的文件突然不见了,尤其是华为安卓系统里的那些重要文件,真是让人心头一紧...
安卓1.5系统软件,初代智能革... 你有没有想过,手机里的那些看似普通的系统,其实背后藏着无数的故事呢?今天,就让我带你走进安卓1.5系...
安卓 代替系统音效设置,打造个... 你有没有发现,手机里的那些系统音效有时候真的让人有点烦躁呢?比如那个每次接电话时“叮咚”一声,或者是...
安卓系统整体性,构建移动设备的... 你知道吗?在智能手机的世界里,安卓系统就像是个全能的魔术师,它不仅拥有丰富的魔法,还能让各种神奇的魔...
安卓系统能玩鬼泣么?,畅享动作... 你有没有想过,在安卓系统上玩《鬼泣》这款游戏会是怎样的体验呢?没错,就是那个让你热血沸腾、挑战极限的...
安卓系统手机编曲软件,音乐创作... 你有没有想过,用手机也能轻松编曲?没错,就是那个你每天不离手的安卓系统手机!现在,我就要给你揭秘几款...
车载导航显示安卓系统,车载导航... 你有没有发现,现在的车载导航系统越来越智能了?尤其是那些搭载了安卓系统的车载导航,简直就像是个贴心的...
安卓系统启动黑屏,安卓系统启动... 手机屏幕突然黑了,这可怎么办?别急,今天就来和你聊聊安卓系统启动黑屏这个让人头疼的问题。你知道吗,这...
怎么解除订阅安卓系统,安卓系统... 你是不是也和我一样,手机里订阅了好多服务,结果现在想解除订阅,却一头雾水?别急,今天就来手把手教你如...
安卓系统停用怎么开启,轻松恢复... 亲爱的手机控们,你是否曾经遇到过安卓系统突然停用的情况,让你手忙脚乱,不知所措?别担心,今天就来教你...
安卓系统电池健康度,电池健康度... 你有没有发现,你的安卓手机最近是不是有点儿不给力了?电池续航能力大不如前,充电速度也慢了不少?别急,...
安卓系统按键怎么截图,安卓系统... 你是不是也和我一样,有时候想截个图分享给朋友,却发现安卓手机的截图功能有点神秘呢?别急,今天就来手把...
购票系统安卓源代码,架构设计与... 你有没有想过,那些我们每天离不开的购票系统,它们背后的秘密是什么呢?今天,就让我带你一探究竟,揭开购...
安卓手机系统后台测试,深度解析... 你有没有发现,你的安卓手机后台总是悄悄地忙碌着?别小看了这些后台程序,它们可是手机系统稳定运行的关键...
安卓系统重启的图标,解锁设备新... 手机突然重启,是不是心里有点慌?别急,今天就来和你聊聊安卓系统重启的图标,让你一眼就能认出它,再也不...
车载智慧屏安卓系统,智能出行新... 你有没有发现,现在的车载智慧屏越来越智能了?尤其是那些搭载了安卓系统的,简直就像是个移动的小电脑,不...
安卓系统连上网权限,解锁设备无... 你有没有发现,你的安卓手机里有些应用总是偷偷连上网?别小看这个小小的网络权限,它可是能影响你隐私、消...
安卓谷歌操作系统,探索安卓谷歌... 你知道吗?在智能手机的世界里,有一个操作系统可是无人不知、无人不晓,那就是安卓谷歌操作系统。它就像一...