Golang Gin HTTP request and parameter parsing

gin network request and routing processing


We introduced the Gin framework, installed the Gin framework, and completed the creation of the first Gin project.

Create Engine

In the gin framework, Engine is defined as a structure, and Engine represents a structure definition of the gin framework, which includes routing groups, middleware, page rendering interfaces, framework configuration settings and other related content. The default Engine can be created by gin.Default, or it can also be created by using gin.New(). The two ways are as follows:

engine1 := gin.Default()
engine2 := gin.New()

The difference between gin.Default() and gin.New() is that gin.Default() also uses gin.New() to create an engine instance, but uses Logger and Recovery middleware by default.

  • Logger is the middleware responsible for printing and outputting logs, which is convenient for developers to debug programs
  • The role of the Recovery middleware is that if a panic interrupts the service during the execution of the program, Recovery will resume the execution of the program and return the server 500 internal error. Normally, we use the default gin.Default to create an Engine instance.

Handle HTTP requests


In the created engine instance, there are many methods that can directly handle different types of HTTP requests.

 

HTTP request type


A total of eight methods or types are defined in the http protocol to indicate different operation methods for requesting network resources (Request-URI), namely: OPTIONS, HEAD, GET, POST, PUT, DELETE, TRACE, CONNECT.

Although there are a total of eight types of request operations, GET POST DELETE and other types are commonly used in actual development.

get means to obtain a network resource from the network, and post means to submit a piece of data to the server. In the process of using, post is often used when there is a form data submission in a certain web page. delete is executed when the resource is deleted.

 If you want to carry data, it will be placed in the body, so that the name of the carried data and the corresponding data will be filled in here. 

 

 

general processing


The engine can directly process the HTTP request, and use the Handle method to process the HTTP request in the engine. The Handle method contains three parameters, as follows:

func (group *RouterGroup) Handle(httpMethod string, relativePath string, handlers ...HandlerFunc) IRoutes
  • httpMethod: The first parameter indicates the HTTP request type to be processed, which is one of the eight request types such as GET, POST, and DELETE.
  • relativePath: The second parameter indicates the interface to be parsed, which is defined by the developer.
  • handlers: The third parameter is the definition of the code that handles the corresponding request. CSDN @ Foxconn Quality Inspector Zhang Quandan

Examples are as follows:

 handler handles GET requests

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

// 使用handle方法处理/hello这样一个请求
func main() {
	//创建engine引擎对象
	engine := gin.Default()
	//请求路径 http://localhost:8080/hello?name=lucas 带参数name
	//匿名函数处理http的请求,context为请求上下文,携带一些属性和方法
	engine.Handle("GET", "/hello", func(c *gin.Context) {
		path := c.FullPath() //请求的接口
		fmt.Println(path)

		//获取参数,最后一个参数是获取不到时候的默认值为hello
		name := c.DefaultQuery("name", "hello")
		fmt.Println(name)

		//输出,处理完请求之后需要返回结果给前端
		c.Writer.Write([]byte("hello " + name))

	})

	engine.Run(":8000")
}

/hello
lucas
[GIN] 2023/04/25 - 10:53:09 | 200 |       333.7µs |       127.0.0.1 | GET      "/hello?name=lucas"

/hello
hello
[GIN] 2023/04/25 - 10:54:11 | 200 |            0s |       127.0.0.1 | GET      "/hello"

The first parameter of the Handle method specifies the processing of GET type requests, and the resolved interface is /hello.

Context is a structure encapsulated in the gin framework, which is the most important and basic structure object in the gin framework.

This structure can provide us with related operations such as operating requests, processing requests, and obtaining data. It is usually called a context object, which simply provides us with an operating environment.

The parameters carried by the GET request can be obtained through context.Query and context.DefaultQuery. Data can be returned to the request initiator through context.Writer.Write.

handler handles post requests 

//post http://localhost:8080/login
	//post请求携带数据不和get上面一样,而是放在请求的body里面,也就是请求体里面
	engine.Handle("POST", "/login", func(c *gin.Context) {
		path := c.FullPath() //请求的接口
		fmt.Println(path)

		//获取post表单当中数据的哪一个字段
		username := c.PostForm("username")
		password := c.PostForm("password")
		fmt.Println("username:", username, "password:", password)

		c.Writer.Write([]byte("username:" + username))
	})

In the above case, the first parameter specifies the request to parse the POST type, and the second parameter specifies the parsed interface as /login. The POST request submits data in the form of a form, and the data fields submitted in the form can be obtained through context.PostForm.

Other types of HTTP requests can also handle corresponding types of requests through the Handle method.

classification processing


In addition to the general processing methods included in the engine, the engine can also perform direct resolution by type. The engine includes get method, post method, delete method and other methods corresponding to the http request type.

engine.GET() handles GET requests

The engine contains the GET method to handle HTTP GET type requests. The GET method of the engine contains two parameters, and the programming usage is as follows:

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	engine := gin.Default()
	//http://127.0.0.1/hello?name=lucas
	engine.GET("/hello", func(c *gin.Context) {
		fmt.Println(c.FullPath())

		//查询携带的字段名称,这个没有默认返回参数
		name := c.Query("name")
		fmt.Println("name:", name)

		c.Writer.Write([]byte("name is:" + name))
	})

	engine.Run()
}


[GIN-debug] Listening and serving HTTP on :8080
/hello
name: lucas
[GIN] 2023/04/26 - 09:06:37 | 200 |       297.4µs |       127.0.0.1 | GET      "/hello?name=lucas"

/hello
name:
[GIN] 2023/04/26 - 09:07:12 | 200 |       950.7µs |       127.0.0.1 | GET      "/hello?name1=lucas"
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	engine := gin.Default()

	engine.POST("/login", func(c *gin.Context) {
		fmt.Println(c.FullPath())

		if name, exits := c.GetPostForm("username"); exits {
			fmt.Println("username is:", name)
		}

		if password, exits := c.GetPostForm("password"); exits {
			fmt.Println("password is:", password)
		}

	})

	engine.Run()
}


[GIN-debug] Listening and serving HTTP on :8080
/login
username is: lucas 
password is: 123456
[GIN] 2023/04/26 - 09:13:34 | 200 |      1.5881ms |       127.0.0.1 | POST     "/login"

 In this place of parsing the interface, through: the value of the custom variable, :id represents the value of the variable,

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	engine := gin.Default()

	engine.DELETE("/user/:id", func(c *gin.Context) {
		userID := c.Param("id")
		fmt.Println("userid is:", userID)
	})

	engine.Run()
}

[GIN-debug] Listening and serving HTTP on :8080
userid is: 24
[GIN] 2023/04/26 - 10:05:25 | 200 |            0s |       127.0.0.1 | DELETE   "/user/24"

 

The above introduces the two most commonly used methods of HTTP processing requests. One is to use handler processing, which needs to specify a specific request type, and the second is the routing method post delete, which handles the response interface type.

The above also introduces how to obtain the data submitted by the client. post get delete.................................. 

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/130358855