1. Introduction of gin

Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.

Gin is a high-performance Web development framework written using Golang

2. Important objects of GIN framework

  • Context: a singlewebA request context object that stores data related to the request and response.ginThe construction starts when the request is receivedContext, which is then processed in turn by the corresponding function chain of the request to generate the final response

  • IRouter: a collection of methods (interfaces) that manage and register routing functions, such asUse/GET/POST/GroupMethods.EngineRouterGroupImplement theIRouterinterface

  • Engine : webThe master engine of the service, providing service configuration and registrationmiddleware, register routing functions, start services, etc., can also be regarded as the root of an empty string prefixRouterGroup

  • RouterGroup: Convenient for developersURLPerform prefix group management on the object it is associated withURLPrefix and the function chain bound to it. Calls to its methods essentially revert back toEngineObject method call

  • HandlersChain: A chain of functions modeled after func(*gin.Context) that can be used to represent either routing functions or middleware

  • HandlerFunc: that is,func(*gin.Context), can represent either a routing function or a routing functionmiddlewareIn general, oneURLMatches one routing function (or more than one)middlewarePlus a routing function), and the routing function is last in the function chain, before the routing functionHandlerFuncGenerally belong tomiddlewareCan be used for parameter verification, exception handling, log printing, and permission authentication.middlewareIt is called only once after the request has been processedcontext.Next()Method is executed as a chain of driving functions

  • MethodTrees: request methodTrees, either registering routes or registering middleware, are essentially adding new nodes to the corresponding methodTree. The different request methods will correspond to a methodTree, and each one can be viewed as a Radix Tree (radix Tree is similar to dictionary tree, supporting path pattern matching). When routing matches, gin will find the corresponding methodTree through the corresponding request method and request path, then traverse the methodTree to find the only node that matches the request path, Node, and execute the HandlersChain bound to that node

    Why not use hash tables to match routes? For the Web framework, the path of the registered routing function generally needs to support dynamic variables or wildcards, such as /books/:book_id, etc. That is to say, the path of the registered routing function is a pattern, and the hash table cannot match pattern. Different paths will be mapped to a unique hash value

3. Gin framework key methods

a). gin.New

Returns without using anymiddlewareEngineThe instance

And something like thatgin.Default(), two are registered by defaultmiddleware 

b). RouterGroup.Use

Will be registeredmiddlewareAdded to theRouterGroupIn the chain of functions 

EngineThere is also the same method, the essence is for the presentEngineThe instanceRouterGroupProperty registrationmiddleware

c). RouterGroup.GET

As long as it is a registered routing function, eitherGET/POST/PUT/PATCH/HEAD/OPTIONS/DELETE/CONNECT/TRACE/ANYAnd so on method, finally callRouterGroup.Handle(httpMethod, relativePath string, handlers HandlersChain)

whileHandleMethods in thehandlesWill be called after the expansionengine.addRoute(method, path string, handlers HandlersChain)EnginemethodTreesThe new node

d). engine.ServeHttp

ginFramework is togolanghttpThe package is encapsulated before executionRunFunction starts listening for requests on a port,

And forhttp.ListenAndServeThe second parameter, which needs to be implementedServeHttpinterface

In the Engine implementation, a brand new *gin.Context is constructed, and then the Context instance is passed into the corresponding routing function chain for processing

It is important to note that sync.Pool is used to manage Context objects, assuming that the higher the QPS requested, the more frequently Context objects are created, which means that gc is more frequent. In order to avoid repeated object creation and destruction, Sync.Pool caches objects that are not in use. When you need them next time, you simply call the pool.Get method to retrieve the cached objects and empty them, so they can be reused

Through the request path and parameter matching request method tree node, get the corresponding node function chain, and then callcontext.Next()Drive the execution of the function chain

4. To summarize

  1. The Engine object is the entry point for configuring or starting a Web service

  2. The RouterGroup object is designed to make it easier for developers to group urls, and operations on it eventually translate to operations on the Engine

  3. Engine maintains a collection of request methodTrees, which add nodes to the corresponding request method tree each time a URL is registered, and traverse the request method tree each time a request is matched to get the target node of the request

  4. Context is used throughout the receipt and response of requests, and is used by the GIN framework to pass between function chains of target nodes, as well as to drive the execution of function chains

Regularly push blog posts related to back-end applications