golang利用context上下文通过中间件传递多个值

首先定义一个context 中间件:

package middleware

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

// ContextValue is a context key
type ContextValue map[string]interface{}

// ContextMiddleware 传递公共参数中间件
func ContextMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        data := ContextValue{
            "1": "one",
            "2": "two",
        }
        // 赋值
        ctx := context.WithValue(r.Context(), "data", data)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

在其他文件或其他中间件中,可以这样使用:

data := r.Context().Value("data").(ContextValue)["2"]
fmt.Println(data) // 会打印 two

参考地址:https://www.it1352.com/808860.html

猜你喜欢

转载自www.cnblogs.com/alpiny/p/12799459.html