package narco import ( "fmt" "net/http" "golang.org/x/net/context" ) 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 { //default to http formatter http.Error(rw, fmt.Sprintf("%s", message), status) return } fmter(ctx, rw, message, status) } 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, `