Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prabirshrestha/c3309751aa0482b737f1 to your computer and use it in GitHub Desktop.
Save prabirshrestha/c3309751aa0482b737f1 to your computer and use it in GitHub Desktop.
strongly typed context in golang - github.com/gohttp/app
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")
}