登录
首页 >  Golang >  Go问答

ServeHTTP如何接受参数?

来源:stackoverflow

时间:2024-02-07 20:18:19 285浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《ServeHTTP如何接受参数?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我想向 gorilla 添加一个中间件,用额外的参数“丰富”调用:

// 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)
    })
}

我想添加 message 作为最终可在路由中使用的参数:

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))
}

这种方法在 go 中可行吗?


正确答案


多亏了注释和指针,我成功地传递了变量。供参考:

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>