douman6245 2018-12-31 14:17
浏览 15

如何在上下文中访问键

FIRST EXAMPLE:

I'm using chi router (github.com/go-chi/chi) and this simple default code:

func main() {
    router := chi.NewRouter()

    router.Group(func(subrouter chi.Router) {

        subrouter.Use(AddContext)

        subrouter.Get("/", func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()

            routeContext := ctx.Value("RouteContext")
            test := ctx.Value("myContextTestKey")

            fmt.Printf("ctx: %+v
", ctx)
            fmt.Printf("routeContext: %+v
", routeContext)
            fmt.Printf("test: %+v
", test)
        })
    })

    srv := &http.Server{
        Addr:    ":" + Port,
        Handler: router,
    }
    err := srv.ListenAndServe()
    CheckErr(err)
}

func AddContext(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := context.WithValue(r.Context(), "myContextTestKey", "myContextTestValue")
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

This is my context if I Printf it:

ctx: context.Background

.WithValue(&http.contextKey{name:"http-server"}, &http.Server{Addr:":3000", Handler:(*chi.Mux)(0xc0002f8840), TLSConfig:(*tls.Config)(0xc000430300), ReadTimeout:0, ReadHeaderTimeout:0, WriteTimeout:0, IdleTimeout:0, MaxHeaderBytes:0, TLSNextProto:map[string]func(*http.Server, *tls.Conn, http.Handler){"h2":(func(*http.Server, *tls.Conn, http.Handler))(0x78b450)}, ConnState:(func(net.Conn, http.ConnState))(nil), ErrorLog:(*log.Logger)(nil), disableKeepAlives:0, inShutdown:0, nextProtoOnce:sync.Once{m:sync.Mutex{state:0, sema:0x0}, done:0x1}, nextProtoErr:error(nil), mu:sync.Mutex{state:0, sema:0x0}, listeners:map[*net.Listener]struct {}{(*net.Listener)(0xc0001222b0):struct {}{}}, activeConn:map[*http.conn]struct {}{(*http.conn)(0xc000149680):struct {}{}, (*http.conn)(0xc000160460):struct {}{}}, doneChan:(chan struct {})(nil), onShutdown:[]func(){(func())(0x7972c0)}})

.WithValue(&http.contextKey{name:"local-addr"}, &net.TCPAddr{IP:net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, Port:3000, Zone:""}).WithCancel.WithCancel

.WithValue(&chi.contextKey{name:"RouteContext"}, &chi.Context{Routes:(*chi.Mux)(0xc0002f8840), RoutePath:"", RouteMethod:"GET", RoutePatterns:[]string{"/"}, URLParams:chi.RouteParams{Keys:[]string(nil), Values:[]string(nil)}, routePattern:"/", routeParams:chi.RouteParams{Keys:[]string(nil), Values:[]string(nil)}, methodNotAllowed:false})

.WithValue("myContextTestKey", "myContextTestValue")

SECOND EXAMPLE:

Using github.com/volatiletech/authboss I'm trying to access context using this code:

router.Use(ab.LoadClientStateMiddleware)

router.Group(func(subrouter chi.Router) {
    subrouter.Use(authboss.Middleware2(ab, 1, 1))
    subrouter.Get("/", func(w http.ResponseWriter, r *http.Request) {
        if user := r.Context().Value("user"); user != nil {
            fmt.Println(user.(auth.User))
        } else {
            fmt.Println("Still nil")
        }
    }
}

and as you can see from this pic:

debugging

the key user is there.

QUESTIONS:

1) Why I can't access it with r.Context().Value("user")? Why alwaysnil`?

2) Why I got nil for routeContext and got correctly myContextTestValue for test var?

3) How to read other keys in my Context?

Note: I don't have this problem just with chi router, I cannot understand how to access keys in context. I know I have to use in .Value() the same type of the key but how to know the type before?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微带串馈天线阵列每个阵元宽度计算
    • ¥15 关于无人驾驶的航向角
    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM
    • ¥15 划分vlan后不通了