douya7121 2019-06-10 09:14
浏览 15
已采纳

如何全局访问处理程序值

I have this simple http server. 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)
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-06-10 09:54
    关注

    You could use net/context with http.Handler. for example you have "X-Request-ID" in header, you could define middlware like this:

    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.

    func handler(rw http.ResponseWriter, req *http.Request) {
        reqID := requestIDFromContext(req.Context())
        fmt.Fprintf(rw, "Hello request ID %v
    ", 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. for more detail information visit this blog.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答