Created
May 31, 2016 15:55
-
-
Save Ell/10a6e2b6fcc6402071011f1fdea3a582 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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