Created
May 4, 2015 19:29
-
-
Save Mistobaan/6b3bfba4418a6e65c39a to your computer and use it in GitHub Desktop.
context Example
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
// 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