From dc107d934dc51b7ea84fcd4c1619a2d86af55f5e Mon Sep 17 00:00:00 2001 From: Alexandre Tuleu Date: Thu, 13 Aug 2015 12:05:01 +0200 Subject: [PATCH] Lints error_formatter.go --- Makefile | 2 +- error_formatter.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 152e90d..478df7c 100644 --- a/Makefile +++ b/Makefile @@ -6,4 +6,4 @@ build: check: go test -coverprofile=cover.out -covermode=count go vet -# golint + golint diff --git a/error_formatter.go b/error_formatter.go index 7a17377..e345621 100644 --- a/error_formatter.go +++ b/error_formatter.go @@ -11,8 +11,13 @@ type narcoKey int const errorFormatterKey narcoKey = 1 +// ErrorFormatter defines a function that can format an HTTP1.1 error +// and is but is Context-aware type ErrorFomatter func(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) +// Error is formatting a in a http.Response an error, like +// http.Error. However it uses the ErrorFormatter in the current +// context to do so, if one is defined with WithErrorFormatter func Error(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) { fmter, ok := ctx.Value(errorFormatterKey).(ErrorFomatter) if ok == false { @@ -25,18 +30,25 @@ func Error(ctx context.Context, rw http.ResponseWriter, message interface{}, sta var narcoDefaultFormatter ErrorFomatter +// TextErrorFormatter is an ErrorFormatter that formats the error by +// just putting plain text func TextErrorFormatter(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) { rw.Header()["Content-Type"] = []string{"text/plain; charset=utf-8"} rw.WriteHeader(status) fmt.Fprintf(rw, "%s", message) } +// BasicHTMLErrorFormatter is an ErrorFormatter that formats the error +// in a very basic HTML page (you may want to write your own with a +// choosen template. func BasicHTMLErrorFormatter(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) { rw.Header()["Content-Type"] = []string{"text/html; charset=utf-8"} rw.WriteHeader(status) fmt.Fprintf(rw, `

Error %d

%s`, status, message) } +// WithErrorFormatter is returning a context where the user has +// defined an ErrorFormatter that Error() should use. func WithErrorFormatter(ctx context.Context, fmter ErrorFomatter) context.Context { return context.WithValue(ctx, errorFormatterKey, fmter) }