全局访问处理程序值的方法
时间:2024-02-29
浏览:122
作者:佚名
学习Golang要努力,但是不要急!今天的这篇文章《全局访问处理程序值的方法》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
我有这个简单的http服务器。我如何访问全局变量的请求数据并在应用程序的任何部分使用它。
package main
import (
"io"
"net/http"
)
var data string // Get URL data globally and use it in other part of the application
func hello(w http.ResponseWriter, r *http.Request) {
data := r.URL.Query().Get("somestring")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", hello)
http.ListenAndServe(":8000", mux)
}解决方案
您可以将 net/context 与 http.handler 一起使用。例如,标头中有“x-request-id”,您可以像这样定义中间件:
func middleware(next http.handler) http.handler {
return http.handlerfunc(func(rw http.responsewriter, req *http.request) {
ctx := newcontextwithrequestid(req.context(), req)
next.servehttp(rw, req.withcontext(ctx))
})
}
type key int
const requestidkey key = 0
func newcontextwithrequestid(ctx context.context, req *http.request) context.context {
reqid := req.header.get("x-request-id")
if reqid == "" {
reqid = generaterandomid()
}
return context.withvalue(ctx, requestidkey, reqid)
}
func requestidfromcontext(ctx context.context) string {
return ctx.value(requestidkey).(string)
}
您可以在任何具有 context 对象的处理程序中获取 requestidkey。
func handler(rw http.ResponseWriter, req *http.Request) {
reqID := requestIDFromContext(req.Context())
fmt.Fprintf(rw, "Hello request ID %v\n", reqID)
}
这只是一个例子。插入 requestidkey 后,您可以将任何数据放入 context 中并使用密钥从中读取。 更多详细信息请访问this博客。
今天关于《全局访问处理程序值的方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
热门专题
