assigning to an http request in a handler

78 views
Skip to first unread message

zilto karamazov

unread,
Dec 21, 2020, 11:49:54 AM12/21/20
to golang-nuts

Hello,

I'm wondering if it is ok to do this ?

////
package main

import (
        "context"
        "fmt"
        "log"
        "net/http"

        "github.com/gorilla/mux"
)

func main() {
        addr := "127.0.0.1:8080"
        r := mux.NewRouter()

        r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                newReq := r.WithContext(context.WithValue(r.Context(), 0, "bla"))
                *r = *newReq
                // set context
        })

        r.Use(func(next http.Handler) http.Handler {
                return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                        next.ServeHTTP(w, r)

                        ctx := r.Context()
                        v, ok := ctx.Value(0).(string)
                        if !ok {
                                fmt.Println("could not find context value")
                        } else {
                                fmt.Println(v)
                        }
                })
        })

        s := &http.Server{
                Addr:    addr,
                Handler: r,
        }

        if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
                log.Fatalf("could not listen on %s : %v", addr, err)
        }
}

////

Uli Kunitz

unread,
Dec 21, 2020, 6:17:01 PM12/21/20
to golang-nuts
I don't think this is a good idea.

I would do something like this.

type mykey struct{}
var key mykey

r.Use(func(next http.Handler) http.Handler {
                return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                        var s string
                        r = r.WithContext(context.WithValue(r.Context(), &key, &s))
                        next.ServeHTTP(w, r)
                        if s != "" {
                                    fmt.Fprint("string %s\n", s)
                        }                      
                })
        })

In the handler itself you must of course get the value by assuming that key will always have string pointer. You can then assign a string to the pointer, which will be output if its non-nil. Wonder whether you want to store a map or a io.Writer as value instead of a single string.

Uli Kunitz

unread,
Dec 21, 2020, 6:18:57 PM12/21/20
to golang-nuts
It should be 

r = r.WithContext(context.WithValue(r.Context(), key, &s))

Using the address of a key was a typo.

Amit Saha

unread,
Dec 21, 2020, 11:36:17 PM12/21/20
to zilto karamazov, golang-nuts
What is the goal you are trying to accomplish here?
Reply all
Reply to author
Forward
0 new messages