如何向ServeHTTP方法添加参数?

huangapple go评论76阅读模式
英文:

How to add parameters to ServeHTTP?

问题

我想要向Gorilla添加一个中间件,用于在调用中添加额外的参数:

// 添加一个名为"message"的参数的中间件
func authCheck(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		message := "hello"
		log.Info().Msgf("添加消息 %v", message)
        // 我的问题核心在这里:如何将"message"传递给下一个处理函数
		next.ServeHTTP(w, r)
	})
}

func main() {
    // (...)
    r.HandleFunc("/check", check).Methods(http.MethodGet)
    // (...)
    r.Use(authCheck)
    // (...)
}

func check(w http.ResponseWriter, r *http.Request) {
    // 我想在这里使用"message",并将其传递给函数
    w.Write([]byte(message))
}

在Go语言中,是否可以采用这种方法呢?

英文:

I would like to add a middleware to Gorilla that "enriches" the call with extra parameters:

// a middleware that adds a parameter "message"
func authCheck(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		message := "hello"
		log.Info().Msgf("adding message %v", message)
        // the core of my question is here: how to pass "message" further
		next.ServeHTTP(w, r)
	})
}

I would like to add message as a parameter that could be ultimately used in a route:

main() {
    // (...)
    r.HandleFunc("/check", check).Methods(http.MethodGet)
    // (...)
    r.Use(authCheck)
    // (...)
}

func check(w http.ResponseWriter, r *http.Request) {
    // I would like to use "message" here, having it passed somehow to the function
	w.Write([]byte(message))
}

Is such an approach possible in Go?

答案1

得分: 1

感谢评论和指导,我成功传递了变量。供参考:

type httpContextStruct struct {
    user  string
    wazaa string
}

var httpContext httpContextStruct

func authCheck(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        httpContext = httpContextStruct{}
        r = r.WithContext(context.WithValue(
            r.Context(),
            httpContext,
            httpContextStruct{
                user:  "thisisme",
                wazaa: "aaa",
            },
        ))
        next.ServeHTTP(w, r)
    })
}

func check(w http.ResponseWriter, r *http.Request) {
    myc := r.Context().Value(httpContext).(httpContextStruct)
    w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}

// 输出
// user: thisisme
英文:

Thanks to the comments and pointers, I managed to pass the variable. For reference:

type httpContextStruct struct {
	user  string
	wazaa string
}

var httpContext httpContextStruct

func authCheck(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		httpContext = httpContextStruct{}
		r = r.WithContext(context.WithValue(
			r.Context(),
			httpContext,
			httpContextStruct{
				user:  "thisisme",
				wazaa: "aaa",
			},
		))
		next.ServeHTTP(w, r)
	})
}

func check(w http.ResponseWriter, r *http.Request) {
	myc := r.Context().Value(httpContext).(httpContextStruct)
	w.Write([]byte(fmt.Sprintf("user: %v", myc.user)))
}

// output
// user: thisisme

huangapple
  • 本文由 发表于 2022年2月9日 16:36:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/71046302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定