// framework/middleware/context.gopackagemiddlewareimport("net/http""github.com/zenazn/goji/web""golang.org/x/net/context")// ContextKey is key name for stored contextconstContextKey="context"// Context creates new Context for new requestfuncContext(c*web.C,hhttp.Handler)http.Handler{fn:=func(whttp.ResponseWriter,r*http.Request){ctx:=context.Background()ctx=context.WithValue(ctx,"request",r)c.Env[ContextKey]=ctxh.ServeHTTP(w,r)}returnhttp.HandlerFunc(fn)}
主程序
Go: main.go
123456789101112131415161718192021222324252627
// main.gopackagemainimport("flag""github.com/zenazn/goji""github.com/zenazn/goji/web""github.com/zenazn/goji/web/middleware"mw"github.com/eure/example-blog-golang/framework/middleware"// <- set alias to avoid name conflict"github.com/eure/example-blog-golang/routing")funcmain(){flag.Set("bind",":1234")// api v1 routingrouteV1:=web.New()routeV1.Use(mw.Context)// <- create contextrouteV1.Use(middleware.SubRouter)goji.Handle("/api/v1/*",routeV1)routing.SetV1(routeV1)// run http servergoji.Serve()}