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")
}

相关内容

热门资讯

【MySQL】锁 锁 文章目录锁全局锁表级锁表锁元数据锁(MDL)意向锁AUTO-INC锁...
【内网安全】 隧道搭建穿透上线... 文章目录内网穿透-Ngrok-入门-上线1、服务端配置:2、客户端连接服务端ÿ...
GCN的几种模型复现笔记 引言 本篇笔记紧接上文,主要是上一篇看写了快2w字,再去接入代码感觉有点...
数据分页展示逻辑 import java.util.Arrays;import java.util.List;impo...
Redis为什么选择单线程?R... 目录专栏导读一、Redis版本迭代二、Redis4.0之前为什么一直采用单线程?三、R...
【已解决】ERROR: Cou... 正确指令: pip install pyyaml
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
Lock 接口解读 前置知识点Synchronized synchronized 是 Java 中的关键字,...
Win7 专业版安装中文包、汉... 参考资料:http://www.metsky.com/archives/350.htm...
3 ROS1通讯编程提高(1) 3 ROS1通讯编程提高3.1 使用VS Code编译ROS13.1.1 VS Code的安装和配置...
大模型未来趋势 大模型是人工智能领域的重要发展趋势之一,未来有着广阔的应用前景和发展空间。以下是大模型未来的趋势和展...
python实战应用讲解-【n... 目录 如何在Python中计算残余的平方和 方法1:使用其Base公式 方法2:使用statsmod...
学习u-boot 需要了解的m... 一、常用函数 1. origin 函数 origin 函数的返回值就是变量来源。使用格式如下...
常用python爬虫库介绍与简... 通用 urllib -网络库(stdlib)。 requests -网络库。 grab – 网络库&...
药品批准文号查询|药融云-中国... 药品批文是国家食品药品监督管理局(NMPA)对药品的审评和批准的证明文件...
【2023-03-22】SRS... 【2023-03-22】SRS推流搭配FFmpeg实现目标检测 说明: 外侧测试使用SRS播放器测...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
初级算法-哈希表 主要记录算法和数据结构学习笔记,新的一年更上一层楼! 初级算法-哈希表...
进程间通信【Linux】 1. 进程间通信 1.1 什么是进程间通信 在 Linux 系统中,进程间通信...
【Docker】P3 Dock... Docker数据卷、宿主机与挂载数据卷的概念及作用挂载宿主机配置数据卷挂载操作示例一个容器挂载多个目...