From 766847a38bea06f1968014fddee1b5d8471ced35 Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Fri, 24 Feb 2017 16:37:59 +0000 Subject: [PATCH] Add helper functions - 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. --- context.go | 6 ++++-- json.go | 15 +++++++++++++++ json_test.go | 4 ++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/context.go b/context.go index d8def4f..f2477a5 100644 --- a/context.go +++ b/context.go @@ -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) } diff --git a/json.go b/json.go index b0834ea..46c5396 100644 --- a/json.go +++ b/json.go @@ -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. diff --git a/json_test.go b/json_test.go index 687db27..3ce03a8 100644 --- a/json_test.go +++ b/json_test.go @@ -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") } }