参考资料

  1. https://study.163.com/course/courseMain.htm?courseId=1210171207 李文周Mooc
  2. https://www.liwenzhou.com/posts/Go/read_gin_sourcecode/#autoid-0-1-3 李文周博客

    Gin实例

    1. func main() {
    2. r := gin.Default()
    3. r.GET("/", func(c *gin.Context) {
    4. c.JSON(200, gin.H{
    5. "status": "ok",
    6. })
    7. })
    8. err := r.Run(":9090")
    9. if err != nil {
    10. log.Printf("start server failed, err: %v\n", err)
    11. }
    12. }

初始化

gin.Defalut()

  1. // 使用gin.Default()创建的Engine包含一个Logger和Recovery的中间件。
  2. func Default() *Engine {
  3. debugPrintWARNINGDefault()
  4. engine := New()
  5. engine.Use(Logger(), Recovery())
  6. return engine
  7. }

gin.New()

  1. // 使用gin.New()创建的Engine不包含任何中间件
  2. // 默认配置:
  3. // - RedirectTrailingSlash: true
  4. // - RedirectFixedPath: false
  5. // - HandleMethodNotAllowed: false
  6. // - ForwardedByClientIP: true
  7. // - UseRawPath: false
  8. // - UnescapePathValues: true
  9. func New() *Engine {
  10. debugPrintWARNINGNew()
  11. engine := &Engine{
  12. RouterGroup: RouterGroup{
  13. Handlers: nil,
  14. basePath: "/",
  15. root: true,
  16. },
  17. FuncMap: template.FuncMap{},
  18. RedirectTrailingSlash: true,
  19. RedirectFixedPath: false,
  20. HandleMethodNotAllowed: false,
  21. ForwardedByClientIP: true,
  22. RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"},
  23. TrustedProxies: []string{"0.0.0.0/0"},
  24. AppEngine: defaultAppEngine,
  25. UseRawPath: false,
  26. RemoveExtraSlash: false,
  27. UnescapePathValues: true,
  28. MaxMultipartMemory: defaultMultipartMemory,
  29. trees: make(methodTrees, 0, 9), // 初始化路由树数量(最多9个HTTP方法)
  30. delims: render.Delims{Left: "{{", Right: "}}"},
  31. secureJSONPrefix: "while(1);",
  32. }
  33. engine.RouterGroup.engine = engine
  34. engine.pool.New = func() interface{} {
  35. return engine.allocateContext()
  36. }
  37. return engine
  38. }

type Engine

  1. // Engine是一个gin框架的实例,包括路由、中间件及其他的一些配置
  2. type Engine struct {
  3. RouterGroup
  4. // Enables automatic redirection if the current route can't be matched but a
  5. // handler for the path with (without) the trailing slash exists.
  6. // For example if /foo/ is requested but a route only exists for /foo, the
  7. // client is redirected to /foo with http status code 301 for GET requests
  8. // and 307 for all other request methods.
  9. RedirectTrailingSlash bool
  10. // If enabled, the router tries to fix the current request path, if no
  11. // handle is registered for it.
  12. // First superfluous path elements like ../ or // are removed.
  13. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  14. // If a handle can be found for this route, the router makes a redirection
  15. // to the corrected path with status code 301 for GET requests and 307 for
  16. // all other request methods.
  17. // For example /FOO and /..//Foo could be redirected to /foo.
  18. // RedirectTrailingSlash is independent of this option.
  19. RedirectFixedPath bool
  20. // If enabled, the router checks if another method is allowed for the
  21. // current route, if the current request can not be routed.
  22. // If this is the case, the request is answered with 'Method Not Allowed'
  23. // and HTTP status code 405.
  24. // If no other Method is allowed, the request is delegated to the NotFound
  25. // handler.
  26. HandleMethodNotAllowed bool
  27. // If enabled, client IP will be parsed from the request's headers that
  28. // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was
  29. // fetched, it falls back to the IP obtained from
  30. // `(*gin.Context).Request.RemoteAddr`.
  31. ForwardedByClientIP bool
  32. // List of headers used to obtain the client IP when
  33. // `(*gin.Engine).ForwardedByClientIP` is `true` and
  34. // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the
  35. // network origins of `(*gin.Engine).TrustedProxies`.
  36. RemoteIPHeaders []string
  37. // List of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or
  38. // IPv6 CIDRs) from which to trust request's headers that contain
  39. // alternative client IP when `(*gin.Engine).ForwardedByClientIP` is
  40. // `true`.
  41. TrustedProxies []string
  42. // #726 #755 If enabled, it will trust some headers starting with
  43. // 'X-AppEngine...' for better integration with that PaaS.
  44. AppEngine bool
  45. // If enabled, the url.RawPath will be used to find parameters.
  46. UseRawPath bool
  47. // If true, the path value will be unescaped.
  48. // If UseRawPath is false (by default), the UnescapePathValues effectively is true,
  49. // as url.Path gonna be used, which is already unescaped.
  50. UnescapePathValues bool
  51. // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
  52. // method call.
  53. MaxMultipartMemory int64
  54. // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
  55. // See the PR #1817 and issue #1644
  56. RemoveExtraSlash bool
  57. delims render.Delims
  58. secureJSONPrefix string
  59. HTMLRender render.HTMLRender
  60. FuncMap template.FuncMap
  61. allNoRoute HandlersChain
  62. allNoMethod HandlersChain
  63. noRoute HandlersChain
  64. noMethod HandlersChain
  65. pool sync.Pool
  66. trees methodTrees // 各类HTTP请求路由树的集合
  67. maxParams uint16
  68. trustedCIDRs []*net.IPNet
  69. }
  70. // 确保Engine实现了IRouter接口
  71. var _ IRouter = &Engine{}

Context

  1. // Contex是gin中最重要的结构,它使我们能使用中间件,管理流,处理和返回JSON数据
  2. type Context struct {
  3. writermem responseWriter
  4. Request *http.Request
  5. Writer ResponseWriter
  6. Params Params
  7. handlers HandlersChain
  8. index int8
  9. fullPath string
  10. engine *Engine
  11. params *Params
  12. // This mutex protect Keys map
  13. mu sync.RWMutex
  14. // Keys is a key/value pair exclusively for the context of each request.
  15. Keys map[string]interface{}
  16. // Errors is a list of errors attached to all the handlers/middlewares who used this context.
  17. Errors errorMsgs
  18. // Accepted defines a list of manually accepted formats for content negotiation.
  19. Accepted []string
  20. // queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()
  21. queryCache url.Values
  22. // formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,
  23. // or PUT body parameters.
  24. formCache url.Values
  25. // SameSite allows a server to define a cookie attribute making it impossible for
  26. // the browser to send this cookie along with cross-site requests.
  27. sameSite http.SameSite
  28. }