官网
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,比较容易吸引人们去学习和理解、也降低了开发者们现有项目的迁移成本。
1、零配置路由器
2、仍然是最快的http路由器和框架。从路由到写入。
3、完整的单元测试套件。
4、Battle tested
5、API被冻结,新版本不会破坏你的代码。
一个对“encoding/json” 100%兼容的高性能插拔的替换
Gin使用 encoding/json
作为默认的json包,但你可以通过从其他标签构建来更改为 jsoniter。
go build -tags=jsoniter .
go build -tags=go_json .
you have to ensure that your cpu support avx instruction
go build -tags="sonic avx" .
Gin默认启用MsgPack渲染功能。但是可以通过指定nomsgpack构建标记禁用此功能。
go build -tags=nomsgpack .
这有助于减少可执行文件的二进制大小
Gin项目可以轻松地部署在任何云提供商上。
如何为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())
}
type Engine struct {
}
gin.Default() 返回一个已经附加了 Logger
和 Recovery
中间件的引擎实例(Engine
)。
// ServeHTTP遵循 http.Handler 接口
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
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
}
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
}
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes// HandlerFunc defines the handler used by gin middleware as return value.
type HandlerFunc func(*Context)
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")
}
上一篇:进制转换0