Table of Contents
Gin's Context source code" >Gin's Context source code
Home Backend Development Golang Gin request process source code analysis

Gin request process source code analysis

Aug 04, 2023 pm 05:26 PM
gin

http service of the standard library

Handler接口就可以注册到标准库的http server中。然后就会启动一个web应用。http请求流程当发生一个http请求的时候,在内部处理的流程是下面这样的:开启一个协程进行请求处理在conn.serve中调用serverHandler.ServeHTTP 函数如果有自己注册的Handle,那么就会调用注册的Handle的ServeHTTP 方法。这里还要注意的2个点如果自己在启动的时候没有注册自己的Handle,那么会采用标准库默认的ServeMux,全局名称为DefaultServeMux。如果请求URI为*并且请求Method为OPTIONS,那么Handle行为会被改成默认的globalOptionsHandler。上述分析的源码为GO 1.18.3。Gin 处理请求的流程前面我们看到只要注册自己的Handle接口到标准库就可以接管请求的处理;那么我们来看一下gin的Handle接口实现。在gin中,handleHTTPRequest就是匹配路径和对应handle 的处理函数。流程大致是这样:获取请求的路径在trees中找到对应的methodTree
Copy after login
  • methodTree中匹配对应路径的处理函数handle
    Copy after login
  • Execute the registered function through the Next method
  • Gin's Context source code

    Before executing the registered function, we found that a sync was used in the ServeHTTP method .Pool, it is actually the reuse of gin.Context.

    Gin request process source code analysis

    Let’s take a look at its structure:

    // 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
     params       *Params
     skippedNodes *[]skippedNode
    
     // This mutex protects Keys map.
     mu sync.RWMutex
      ...
    }
    Copy after login

    The official req and resp will be saved in Context in. And gin has added an extension to the official http.ResponseWriter function, that is, it has defined an interface gin.ResponseWriter

    Others Some methods are packages for daily use to facilitate development.

    Context's Bind class method analysis

    Gin request process source code analysis

    In the source code, you can see that a total of Binding supports these ;The implementation is deserialization, the details will not be discussed one by one.

    The key point is that after bind is completed, there is a validate method, which is actually used github.com/go-playground/validator/v10As a library for verifying data.

    Gin request process source code analysis

    And use lazy loading to initialize, which means that if you don’t use it, the object will not be initialized.

    Gin request process source code analysis

    For the development process of validating data, please see the detailed usage of validator[1].

    In the mode.go file of gin, there are controls for some behaviors. For example, DisableBindValidation can turn off the data validation function, which is Call this method before the service starts to shut down.

    Gin request process source code analysis

    ginS folder

    This folder defines a default internal global gin.Engine object.

    Gin request process source code analysis

    And it is also initialized using lazy loading.

    Gin request process source code analysis

    So if you want to use the global gin.Engine, you can use this package, so you don’t have to save your own global gin. Engine object.

The above is the detailed content of Gin request process source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to combine Go with Gin to export Mysql data to Excel table How to combine Go with Gin to export Mysql data to Excel table May 26, 2023 pm 09:15 PM

1. To achieve the goal, Golang uses excelize to export the table to the browser for downloading or saving it locally. The subsequent import will also be written here 2. The library used gogetgithub.com/xuri/excelize/v23, the project directory go-excel├─app│├─excelize││└─excelize.go│├─model││└─ sysUser.go│└─service│└─userService.go├─common│└─mysql.go├─go.mod├─go.sum├─main.go└─setting.json4. Main code writing

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

Go language development essentials: 5 popular framework recommendations Go language development essentials: 5 popular framework recommendations Mar 24, 2024 pm 01:15 PM

"Go Language Development Essentials: 5 Popular Framework Recommendations" As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

How to handle static resource files in the Gin framework How to handle static resource files in the Gin framework Jun 23, 2023 am 10:54 AM

The Gin framework is a lightweight, fast, and flexible web framework that allows developers to build high-performance web applications through a simple and beautiful API. In web applications, static resource files (such as images, CSS, JavaScript, fonts, etc.) are usually unchanged, so these resource files need to be processed efficiently to improve application performance. In the Gin framework, processing static resource files is very simple. This article will introduce how to handle static resource files in the Gin framework. 1. In G

Explore the Go language framework: 5 choices not to be missed! Explore the Go language framework: 5 choices not to be missed! Feb 19, 2024 pm 02:29 PM

As a fast and efficient programming language, Go language has always been favored by programmers. In the Go language ecosystem, frameworks play a vital role in helping developers build applications faster. This article will introduce five Go language frameworks to let you understand their characteristics and usage. 1. Gin framework The Gin framework is a lightweight Web framework with fast and high performance characteristics. Use the Gin framework to quickly build RESTful APIs and web applications. Here is a simple example code:

Detailed explanation of API documentation and automated testing in the Gin framework Detailed explanation of API documentation and automated testing in the Gin framework Jun 22, 2023 pm 09:43 PM

Gin is a web framework written in Golang. It has the advantages of efficiency, lightweight, flexibility, relatively high performance, and easy to use. In Gin framework development, API documentation and automated testing are very important. This article will take an in-depth look at API documentation and automated testing in the Gin framework. 1. API documentation API documentation is used to record the detailed information of all API interfaces to facilitate the use and understanding of other developers. The Gin framework provides a variety of API documentation tools, including Swagger, GoSwa

What are the most popular golang frameworks on the market? What are the most popular golang frameworks on the market? Jun 01, 2024 pm 08:05 PM

The most popular Go frameworks at present are: Gin: lightweight, high-performance web framework, simple and easy to use. Echo: A fast, highly customizable web framework that provides high-performance routing and middleware. GorillaMux: A fast and flexible multiplexer that provides advanced routing configuration options. Fiber: A performance-optimized, high-performance web framework that handles high concurrent requests. Martini: A modular web framework with object-oriented design that provides a rich feature set.

Gin request process source code analysis Gin request process source code analysis Aug 04, 2023 pm 05:26 PM

The official req and resp will be saved in Context. And gin itself has added an extension to the official http.ResponseWriter function, that is, it has defined an interface gin.ResponseWriter.

See all articles