1. Introduction
In this article, we are going to implement a simple web application throughGin
Framework to build. It mainly supports user registration and login. Users can create their own account by registering an account and authenticate through the login function.
Through this article, you will master the useGin
The basic steps of a framework to build a web application, and also understand some of the basic principles of it, so as toGin
A better understanding of the process of building a web application.
2. Basic instructions
Gin
It is a Go web framework with efficient, lightweight, flexible and applicable HTTP routing capabilities. useGin
Framework, we can specify processing functions for HTTP requests, that is, after receiving the request, the Gin framework will find the corresponding processing functions based on the request path and request method, and execute the corresponding business logic.
In useGin
When building a web application in the framework, we need to implement two steps, first of all, start the server and listen to user requests. useGin
The framework starts the server very simple, just call it()
Method creates a default Gin instance and then calls it using that instanceRun()
Method to start the server. For example:
r := () ()
Then we need to specify a processing function for HTTP requests. When building a web application using the Gin framework, we need to specify a processing function for different request paths and request methods. The Gin framework provides a variety of ways to implement this function, the most commonly used one isand
, here we are
Make instructions.
We can passDefine a processing function and use
()
、()
Such methods bind the processing function to the corresponding request path and request method. For example:
func registerHandler(c *) { // Registration logic...} func loginHandler(c *) { // Login logic...} r := () ("/register", registerHandler) ("/login", loginHandler)
In the above code, we defineregisterHandler
andloginHandler
Two processing functions and bind them to/register
and/login
on the path on the GET and POST requests.
To sum up, useGin
Framework construction Web applications require two steps: start the server and listen to user requests, and specify processing functions for HTTP requests. passGin
Providedand
Method, we can quickly complete the above tasks.
3. Basic implementation
Through the above description, we have learned about the useGin
There are two steps to build a web application framework. Based on this, we implement a web application that can receive user registration and login requests. The code example is as follows:
import ( "/gin-gonic/gin" "net/http" ) func main() { // 1. Create an instance by r := () // 2. Set up the routing through GET/POST in ("/register", func(c *) { (, "Registered successfully") }) ("/login", func(c *) { // Process user-submitted data //... // Return the response result (, { "message": "Login successfully", }) }) // 3. Start the server (":8080") }
In the above example code, line 8 passesMethod to create a
instance; line 10 through which
GET
The method uses routing registration, that is, specify a processing function for the request. Here we registerregister
andlogin
Two routes, support registration and login; at line 23, callIn the example
Run
Method: Start the server and listen to the local machine8080
port.
After the program starts, it will listen8080
After the request for the port comes, different business logic will be executed according to the settings of the routing rules. For example, the following is a registration request:
curl http://localhost:8080/register
The following data will be returned:
Registered successfully
4. Explanation of principle
4.1 Why is the setting of routing rules still differentiating between GET and POST methods?
Looking back at the previous routing rules, you can find that there are existing onesGET
Method, andPOST
The method is roughly as follows:
r := () ("/register", func(c *) {}) ("/login", func(c *) {})
WhyWhen setting up the route, it provides
GET
Methods, also providedPOST
What about the method, is this use?
This is actually corresponding to the HTTP protocol. In the HTTP protocol, common request methods include GET, POST, DELETE, PATCH, PUT, OPTIONS, HEAD, etc. These request methods are different in terms of semantics and functions, and different methods will be selected for use according to needs in actual applications.
For example, in the HTTP protocolGET
Methods are generally used to read data operations, andPOST
Methods are generally used to create or modify data operations.
Gin
In the framework, we can useGET
、POST
、DELETE
、PATCH
、PUT
、OPTIONS
、HEAD
etc. to define the corresponding routes and are used to handle different types of requests.Gin
The corresponding route will be automatically matched according to the request method and the corresponding processing function will be called for processing. By distinguishing different request methods, the code can be made clearer and more standardized and reduce errors caused by request conflicts.
Here is an example to illustrate. If we define two routing rules for the same URL, but one usesGET
Method to set, this routing rule will only handle HTTP GET requests; the other one usesPOST
Method to set, this routing rule will only handle HTTP POST requests. Here is a code example:
r := () ("/hello", func(c *) { (, { "message": "hello GET", }) }) ("/hello", func(c *) { (, { "message": "hello POST", }) })
At this time, the server is started, and the client initiates an HTTP GET request to the server, as follows:
curl -X GET http://localhost:8080/hello
At this time, the following data will be returned, indicating that it has been mapped toGET
Routing rules set by method:
{"message":"hello GET"}
4.2 How are routing rules stored
Gin
The storage of routing rules in the is implemented through the prefix tree, and thenGET
,POST
Methods will define a prefix tree separately and do not interfere with each other. Here is an example, for example, there are the following three routing rules:
Here are threeGET
The requested routing rules will be specifically forGET
A request to generate a prefix tree, which contains the above three rules, as follows:
(Root node) / `/user` / \ `j` `:id` / \ `ohn` `ane`
If the routing rules exist at the same timeGET
andPOST
Method, two prefix trees will be generated at this time, and the rules are as follows:
("/user/john", func(c *) {}) ("/user/jane", func(c *) {}) ("/user/:id", func(c *) {}) ("/user/john", func(c *) {}) ("/user/jane", func(c *) {})
Based on this rule, two prefix trees will be generated.GET
Routing rules andPOST
Routing rules do not interfere with each other:
(GETRoot node) (POSTRoot node) / / `/user` `/user` / \ / `j` `:id` `j` / \ / \ `ohn` `ane` `ohn` `ane`
ThenGET
Request, will arriveGET
prefix tree, finds the requested processing function according to the corresponding routing rules;POST
Request to arrivePOST
In the prefix tree of , find the corresponding processing function and execute the corresponding business logic, and the two do not interfere with each other.
5. Summary
This article describes how to use itGin
Framework to build Go web applications. It is mainly divided into two parts: one is the specific steps and the other is the relevant principles.
In the first part, we list the steps to build a web application and provide sample code to help readers understand. The second part explains three common questions, including how routing rules are stored and why it is necessary to distinguish them.GET
andPOST
methods, etc., to help readers better understand the code in the first part.
Through the introduction of this article, readers can learn how to use itGin
The framework uses methods and techniques to quickly develop web applications, while also providing a deeper understanding of the principles and mechanisms behind them. Hope it helps you.
The above is the detailed content of the method of using Gin to build a Go Web application. For more information about Gin to build a Go Web program, please follow my other related articles!