package narco import ( "fmt" "net/http" "golang.org/x/net/context" ) type narcoKey int const errorFormatterKey narcoKey = 1 type ErrorFomatter func(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) func Error(ctx context.Context, rw http.ResponseWriter, message interface{}, status int) { fmter, ok := ctx.Value(errorFormatterKey).(ErrorFomatter) if ok == false { //default to http formatter http.Error(rw, fmt.Sprintf("%s", message), status) return } fmter(ctx, rw, message, status) } var narcoDefaultFormatter ErrorFomatter 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) } 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) } func WithErrorFormatter(ctx context.Context, fmter ErrorFomatter) context.Context { return context.WithValue(ctx, errorFormatterKey, fmter) }