一. 写在前面:
Gin版本: v1.5.0
Gin是Go最流行的Lib(目前排名仅次于Logrus),使用方便,可扩展性好.源码量也不大,组织的也很好,读起来很舒服.也是因为人人都用,况且各路大神总结的都很好,各个方面都讲到了.这里也就大概整理下.
二. Gin使用
-
官方文档:
https://gin-gonic.com/zh-cn/docs/
https://github.com/gin-gonic/examples -
bilibili视频教程
https://www.bilibili.com/video/av73142413
三. 源码分析
1. 依赖
依赖 | 说明 |
---|---|
sse | Server-sent events-需要浏览器端支持服务器推送 |
validator/v10 | 验证器 |
protobuf | google的二进制传输协议,Http/2 |
json-iterator/go | 可选的JSON工具包,在interna/json中可配置,默认用原生的. |
go-isatty | 判断终端类型的LIB |
testify | 测试工具 |
go/codec | 编码工具 |
yaml.v2 | 对yaml格式的支持 |
2. 源码说明
源码分析就太多了,推荐几个感觉写的比较好的.
Go Gin源码学习系列
https://segmentfault.com/a/1190000019101583
https://segmentfault.com/a/1190000019111688
https://segmentfault.com/a/1190000019130634
https://segmentfault.com/a/1190000019149860
https://segmentfault.com/a/1190000019182024
Golang Gin 实战系列
https://www.flysnow.org/2019/12/10/golang-gin-quick-start.html
https://www.flysnow.org/2019/12/12/golang-gin-restful-api.html
https://www.flysnow.org/2019/12/13/golang-gin-parameters-in-path.html
https://www.flysnow.org/2019/12/15/golang-gin-query-parameters-source-code-analysis.html
https://www.flysnow.org/2019/12/18/golang-gin-query-parameters-array-map.html
https://www.flysnow.org/2019/12/23/golang-gin-form-data.html
https://www.flysnow.org/2019/12/25/golang-gin-group-router.html
https://www.flysnow.org/2019/12/29/golang-gin-json-rendering.html
https://www.flysnow.org/2020/01/01/golang-gin-jsonp-and-hijacking.html
https://www.flysnow.org/2020/01/03/golang-gin-xml-rendering.html
https://www.flysnow.org/2020/01/09/golang-gin-html-rendering.html
四. 个人心得
- Gin通过binding包解析httpRequest,并且能做到VO对应,自动把Request中的Body对应到具体的结构体中,比起原生的Http进一步减轻了具体的工作.
- Gin通过Render包构造Response,通过统一的Render方法把各种结构写入REpsonse中去.
- Gin核心结构 - Context
// Context is the most important part of gin. It allows us to pass variables between middleware,
// manage the flow, validate the JSON of a request and render a JSON response for example.
type Context struct {
writermem responseWriter
Request *http.Request
Writer ResponseWriter
Params Params
handlers HandlersChain
index int8
fullPath string
engine *Engine
// Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{}
// 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 use url.ParseQuery cached the param query result from c.Request.URL.Query()
queryCache url.Values
// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,
// or PUT body parameters.
formCache url.Values
}
Context结构把请求,返回都放一起了,这样写Handler就更方便了.
网友评论