Last active
August 29, 2015 14:17
-
-
Save prabirshrestha/c3309751aa0482b737f1 to your computer and use it in GitHub Desktop.
strongly typed context in golang - github.com/gohttp/app
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/gohttp/app" | |
"github.com/gorilla/context" | |
) | |
type Context struct { | |
Name string | |
} | |
type ContextHandler func(w http.ResponseWriter, r *http.Request, ctx *Context) | |
func (h ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
ctx := context.Get(r, "Context") | |
if ctx == nil { | |
ctx = NewRequestContext(r) | |
context.Set(r, "Context", ctx) | |
} | |
h(w, r, ctx.(*Context)) | |
} | |
func NewRequestContext(r *http.Request) *Context { | |
return &Context{ | |
Name: "", | |
} | |
} | |
func main() { | |
a := app.New() | |
// example middleware without context using only go builtins | |
a.Use(func(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Println(r.RequestURI) | |
next.ServeHTTP(w, r) | |
}) | |
}) | |
// example middleware with strongly typed context | |
a.Use(func(next http.Handler) http.Handler { | |
return ContextHandler(func(w http.ResponseWriter, r *http.Request, ctx *Context) { | |
name := r.URL.Query().Get("name") | |
if name == "" { | |
name = "Guest" | |
} | |
ctx.Name = name | |
next.ServeHTTP(w, r) | |
}) | |
}) | |
// example route without context using only go builtins | |
a.Get("/", func(w http.ResponseWriter, r *http.Request) { | |
http.Redirect(w, r, "/hi", http.StatusMovedPermanently) | |
}) | |
// example route using strongly typed context | |
a.Get("/hi", ContextHandler(func(w http.ResponseWriter, r *http.Request, ctx *Context) { | |
fmt.Fprintf(w, "Hi %s", ctx.Name) | |
})) | |
a.Listen(":3000") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Recommended readings: