Skip to content

Instantly share code, notes, and snippets.

@Ell
Created May 31, 2016 15:55
Show Gist options
  • Save Ell/10a6e2b6fcc6402071011f1fdea3a582 to your computer and use it in GitHub Desktop.
Save Ell/10a6e2b6fcc6402071011f1fdea3a582 to your computer and use it in GitHub Desktop.
package server
import (
"encoding/json"
"golang.org/x/net/context"
"net/http"
)
// ContextHandler interface wrapper for ServeHTTPContext
type ContextHandler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}
// ContextHandlerFunc type for context handler wrapper
type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error
// ServeHTTPContext wraps ServeHTTPContext
func (f ContextHandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
return f(ctx, w, req)
}
// ContextAdapter adapts middleware for context awareness
type ContextAdapter struct {
ctx context.Context
handler ContextHandler
}
func (ca *ContextAdapter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
err := ca.handler.ServeHTTPContext(ca.ctx, w, req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"status": "error",
"message": err.Error(),
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment