Skip to content

Commit

Permalink
Add helper functions
Browse files Browse the repository at this point in the history
- Add `NewJSONRequestHandler` which takes a `func` and turns it into
  a `JSONRequestHandler`. This prevents the same wrapping code being
  written over and over.
- Make `GetLogger(Context)` always return a logger, so callers don't
  need to constantly `nil` check.
  • Loading branch information
kegsay committed Feb 24, 2017
1 parent ccef6dc commit 766847a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
6 changes: 4 additions & 2 deletions context.go
Expand Up @@ -25,11 +25,13 @@ func GetRequestID(ctx context.Context) string {
// ctxValueLogger is the key to extract the logrus Logger.
const ctxValueLogger = contextKeys("logger")

// GetLogger retrieves the logrus logger from the supplied context. Returns nil if there is no logger.
// GetLogger retrieves the logrus logger from the supplied context. Always returns a logger,
// even if there wasn't one originally supplied.
func GetLogger(ctx context.Context) *log.Entry {
l := ctx.Value(ctxValueLogger)
if l == nil {
return nil
// Always return a logger so callers don't need to constantly nil check.
return log.WithField("context", "missing")
}
return l.(*log.Entry)
}
15 changes: 15 additions & 0 deletions json.go
Expand Up @@ -58,6 +58,21 @@ type JSONRequestHandler interface {
OnIncomingRequest(req *http.Request) JSONResponse
}

// jsonRequestHandlerWrapper is a wrapper to allow in-line functions to conform to util.JSONRequestHandler
type jsonRequestHandlerWrapper struct {
function func(req *http.Request) JSONResponse
}

// OnIncomingRequest implements util.JSONRequestHandler
func (r *jsonRequestHandlerWrapper) OnIncomingRequest(req *http.Request) JSONResponse {
return r.function(req)
}

// NewJSONRequestHandler converts the given OnIncomingRequest function into a JSONRequestHandler
func NewJSONRequestHandler(f func(req *http.Request) JSONResponse) JSONRequestHandler {
return &jsonRequestHandlerWrapper{f}
}

// Protect panicking HTTP requests from taking down the entire process, and log them using
// the correct logger, returning a 500 with a JSON response rather than abruptly closing the
// connection. The http.Request MUST have a ctxValueLogger.
Expand Down
4 changes: 2 additions & 2 deletions json_test.go
Expand Up @@ -164,8 +164,8 @@ func TestGetLogger(t *testing.T) {

noLoggerInReq, _ := http.NewRequest("GET", "http://example.com/foo", nil)
ctxLogger = GetLogger(noLoggerInReq.Context())
if ctxLogger != nil {
t.Errorf("TestGetLogger wanted nil logger, got '%v'", ctxLogger)
if ctxLogger == nil {
t.Errorf("TestGetLogger wanted logger, got nil")
}
}

Expand Down

0 comments on commit 766847a

Please sign in to comment.