[Go] Demonstrate how to use the context package in Go language

Table of contents

Demonstrates how to use the context package in Go


contextDemonstrates how to use packages in the Go language

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"
)

func handler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// 从Context中获取请求ID
	requestID := ctx.Value("requestID").(string)

	// 模拟处理耗时操作
	time.Sleep(2 * time.Second)

	fmt.Fprintf(w, "Request ID: %s\n", requestID)
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 创建一个带有取消信号的Context
		ctx, cancel := context.WithCancel(r.Context())
		defer cancel()

		// 为Context添加请求ID
		requestID := generateRequestID()
		ctx = context.WithValue(ctx, "requestID", requestID)

		// 设置截止时间为5秒后
		ctx, _ = context.WithTimeout(ctx, 5*time.Second)

		// 执行处理函数
		handler(ctx, w, r)
	})

	http.ListenAndServe(":8080", nil)
}

func generateRequestID() string {
	// 在实际应用中,可以根据需要生成唯一的请求ID
	return "12345678"
}

In the above example, we defined a handlerfunction as HTTP request handler. This function receives a context.Contextparameter representing the context of the request.

In mainthe function, we use http.HandleFunc()the function to set the handler function of the root path as an anonymous function. In this anonymous function, we create one with a cancel signal context.Context, then use context.WithValue()a function to add the request id, and finally use context.WithTimeout()a function to set the deadline.

In the handler function, we extract the request ID Contextfrom it and fmt.Fprintf()write it into the response body via the function. At the same time, we simulate a time-consuming operation in order to demonstrate how deadlines can be used.

You can run the code in the terminal and visit it in the browser http://localhost:8080/to see the effect. Note that there will be a delay in page loading due to the 2-second sleep time.

This is just a simple example to show how to use packages in Go language context. You can use it according to specific needs and scenarios context, such as passing authentication information, controlling concurrency, and so on.

Guess you like

Origin blog.csdn.net/fanjufei123456/article/details/132103023