简体   繁体   English

如何全局访问处理程序值

[英]How to access handler value globally

I have this simple http server. 我有这个简单的http服务器。 How can i access the request data to a global variable and use it in any part of the application. 我如何才能将请求数据访问到全局变量并在应用程序的任何部分中使用它。

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

You could use net/context with http.Handler. 您可以将net / context与http.Handler一起使用。 for example you have "X-Request-ID" in header, you could define middlware like this: 例如,您的标头中包含“ 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)
}

you could get requestIDKey in any handler with Context object. 您可以在带有Context对象的任何处理程序中获取requestIDKey。

func handler(rw http.ResponseWriter, req *http.Request) {
    reqID := requestIDFromContext(req.Context())
    fmt.Fprintf(rw, "Hello request ID %v\n", reqID)
}

this is just an example. 这只是一个例子。 insted of requestIDKey you could have any data which you should put in Context and read from it with a key. 在requestIDKey的插入下,您可以拥有应该放入Context并使用密钥从中读取的任何数据。 for more detail information visit this blog. 有关更多详细信息,请访问博客。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM