Lints error_formatter.go
This commit is contained in:
2
Makefile
2
Makefile
@@ -6,4 +6,4 @@ build:
|
||||
check:
|
||||
go test -coverprofile=cover.out -covermode=count
|
||||
go vet
|
||||
# golint
|
||||
golint
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user