Created
December 9, 2012 16:07
-
-
Save surma/4245799 to your computer and use it in GitHub Desktop.
Gorilla Side Effects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
"github.com/gorilla/context" | |
) | |
func main() { | |
r := mux.NewRouter() | |
r.PathPrefix("/subhandler").Handler(Wrapper(http.StripPrefix("/subhandler", NewHandler()))) | |
http.ListenAndServe("localhost:8080", r) | |
} | |
type Handler struct{ | |
*mux.Router | |
} | |
func NewHandler() *Handler { | |
h := &Handler{} | |
h.Router = mux.NewRouter() | |
h.Router.Path("/").HandlerFunc(func (w http.ResponseWriter, r *http.Request){ | |
fmt.Fprintf(w, "Root!\n") | |
}) | |
h.Router.Path("/bla").HandlerFunc(func (w http.ResponseWriter, r *http.Request){ | |
fmt.Fprintf(w, "/bla\n") | |
}) | |
return h | |
} | |
// Comment this in to disable the mux.Router and make the context work again | |
// func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// } | |
func Wrapper(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("Pointer before delegation: %p\n", r) | |
context.Set(r, "id", "the_id") | |
h.ServeHTTP(w, r) | |
log.Printf("Pointer after delegation: %p\n", r) | |
fmt.Fprintf(w, "Also, your id is: %s\n", context.Get(r, "id").(string)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment