Skip to content

Instantly share code, notes, and snippets.

@Mistobaan
Created May 4, 2015 19:29
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 Mistobaan/6b3bfba4418a6e65c39a to your computer and use it in GitHub Desktop.
Save Mistobaan/6b3bfba4418a6e65c39a to your computer and use it in GitHub Desktop.
context Example
// Default HTTP handler
type Handler func(ctx *Context, w http.ResponseWriter, r *http.Request) error
// ServeHTTP implements http.Handler for our custom type Handler
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx = NewContext(r)
defer ctx.Cancel()
err := h(ctx, w, r)
code := http.StatusOK
switch err {
case nil:
return
case services.ErrNotAuthorized:
code = http.StatusUnauthorized
case services.ErrConflict:
code = http.StatusConflict
default:
code = http.StatusInternalServerError
}
renderError(w, code, err)
}
// Context is our context implementation
type Context struct {
context.Context
uuid uuid.UUID
logger *log.Logger
cancelFunc context.CancelFunc
}
// inspired from https://github.com/golang/appengine/blob/master/appengine.go
func NewContext(req *http.Request) *Context {
ctx, cancel = context.WithTimeout(context.Background(), DefaultHandlerTimeout)
u := uuid.NewV4()
logger := log.New(os.Stderr, u.String()+": ", logFlags)
return &Context{
Context: ctx,
uuid: u,
logger: logger,
cancelFunc: cancel,
}
}
func (ctx *Context) Cancel() {
ctx.cancelFunc()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment