SoFunction
Updated on 2025-03-06

Golang explains in detail the application of commonly used Http libraries and Gin frameworks

1. Http standard library

1.1 http client

func main() {
	response, err := ("")
	if err != nil {
		return
	}
	defer ()
	bytes, err := (response, true)
	if err != nil {
		return
	}
	("%s", bytes)
}

1.2 Custom request header

func main() {
	request, err := (, "", nil)
	if err != nil {
		return
	}
	//Custom request header	("header", "value")
	response, err := (request)
	if err != nil {
		return
	}
	defer ()
	bytes, err := (response, true)
	if err != nil {
		return
	}
	("%s", bytes)
}

1.3 Check Request Redirection

//Check the redirect function	client := {CheckRedirect: func(req *, via []*) error {
		// via: All redirected paths		// req: The path currently redirected		return nil
	}}
	response, err := (request)
	if err != nil {
		return
	}

1.4 http server performance analysis

Graphviz is required to use the graph interface

Import: _ "net/http/pprof", underscore means that only the dependencies are used, and if you don't add them, you will compile and report an error.

Visit: /debug/pprof

use:

  • go tool pprof http://localhost:8888/debug/pprof/profile can view the CPU usage rate for 30 seconds
  • go tool pprof http://localhost:6060/debug/pprof/block View goroundine blocking configuration file

2. JSON data processing

2.1 Entity Serialization

type Order struct {
	ID string
	Name string
	Quantity int
	TotalPrice float64
}
func main() {
	o := Order{ID: "1234", Name: "learn go", Quantity: 3, TotalPrice: 30.0}
	("%+v\n", o)
	//Serialized byte slice,	bytes, err := (o)
	if err != nil {
		return
	}
	("%s\n", bytes)
}

Note: The first letter is lowercase, Marshal will not be serialized

2.2 Processing fields are underlined in lowercase

Use attribute tags

type Order struct {
	ID string `json:"id""`
	Name string `json:"name"`
	Quantity int `json:"quantity"`
	TotalPrice float64 `json:"total_price"`
}
func main() {
	o := Order{ID: "1234", Name: "learn go", Quantity: 3, TotalPrice: 30.0}
	("%+v\n", o)
	//Serialization	bytes, err := (o)
	if err != nil {
		return
	}
	("%s\n", bytes)
}

2.3 Omit empty fields

Add omitempty on a field to omit empty words

type Order struct {
	ID string `json:"id""`
	Name string `json:"name,omitempty"`
	Quantity int `json:"quantity"`
	TotalPrice float64 `json:"total_price"`
}

2.4 Deserialization

func main() {
	//Deserialization	str := `{"id":"1234","name":"learn go","quantity":3,"total_price":30}`
	order := unmarshal[Order](str, Order{})
	("%+v\n", order)
}
//Use generic methods to parse the corresponding entity classfunc unmarshal[T any](str string, t T) any {
	err := ([]byte(str), &t)
	if err != nil {
		return nil
	}
	return t
}

3. Natural Language Processing

You can call Alibaba Cloud's natural language processing API for data processing

3.1 Using Map to process

func mapUnmarshall() {
	str := `{
		"data": [
			{
				"id": 0,
				"word": "please",
				"tags": [
					"Basic Words-Chinese"
				]
			},
			{
				"id": 1,
				"word": "enter",
				"tags": [
					"Basic Words-Chinese",
					"Product Type Modification"
				]
			},
			{
				"id": 2,
				"word": "text",
				"tags": [
					"Basic Words-Chinese",
					"Product Type Modification"
				]
			}
		]
	  }`
	//Map uses interface to store data	m := make(map[string]any)
	err := ([]byte(str), &m)
	if err != nil {
		return
	}
	//If you need to take data with id 2, you need to indicate that the value you get is a slice Use type assertion, including when fetching subsequent data, you must specify the type	("%+v\n", m["data"].([]any)[2].(map[string]any)["tags"])
}

3.2 Defining entity processing

//Map uses interface to store datam := struct {
    Data []struct{
        Id   int32    `json:"id"`
        Word string   `json:"word"`
        Tags []string `json:"tags"`
    } `json:"data"`
}{}
err := ([]byte(str), &m)
if err != nil {
    return
}
("%+v\n", [2].Tags)

4. http framework

4.1 gin

Download dependencies: go get -u /gin-gonic/gin, go get -u /zap (log library)

4.1.1 Start the service

func main() {
	r := ()
	("/ping", func(c *) {
		(200, {
			"message": "pong",
		})
	})
	() // listen and serve on 0.0.0.0:8080
}

4.1.2 middleware

The Context structure contains the request-related information

You can add "interceptor" to web services, add middleware intercept requests to print the log you need

logger, _ := ()
(printRequestLog, printHello)
//If you add multiple methods, first define the method and add it directlyfunc printRequestLog(c *) {
	("Incoming request", ("path", ))
	//Releasing, if not released, the subsequent processing cannot be carried out.	()
    //Get the response object	("Processing status:", ("status", ()))
}
func printHello(c *) {
	("hello:", )
	//Releasing, if not released, the subsequent processing cannot be carried out.	()
}

4.1.3 Set the request ID

func setRequestId(c *) {
	("requestId", ())
	()
}

This is the end of this article about Golang's detailed explanation of the applications of commonly used Http libraries and Gin frameworks. For more related content of Golang Http libraries, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!