Lints error_formatter.go

This commit is contained in:
2015-08-13 12:05:01 +02:00
parent 4785e489d5
commit dc107d934d
2 changed files with 13 additions and 1 deletions

View File

@@ -6,4 +6,4 @@ build:
check:
go test -coverprofile=cover.out -covermode=count
go vet
# golint
golint

View File

@@ -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, `<!doctype html><html><body><h1>Error %d</h1>%s</body></html>`, 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)
}