Documentation ¶
Overview ¶
Package httpe provides http server utilities.
Index ¶
- Variables
- func NewHandler(h HandlerE, ew ErrWriter) http.Handler
- func NewHandlerFunc(h HandlerFuncE, ew ErrWriterFunc) http.HandlerFunc
- func NewSafeHandler(h HandlerE) http.Handler
- func NewSafeHandlerFunc(h HandlerFuncE) http.HandlerFunc
- func WriteSafeErr(w http.ResponseWriter, err error)
- type ErrWriter
- type ErrWriterFunc
- type HandlerE
- type HandlerFuncE
- type StatusError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadRequest = StatusError(http.StatusBadRequest) ErrPaymentRequired = StatusError(http.StatusPaymentRequired) ErrForbidden = StatusError(http.StatusForbidden) ErrNotFound = StatusError(http.StatusNotFound) ErrMethodNotAllowed = StatusError(http.StatusMethodNotAllowed) ErrNotAcceptable = StatusError(http.StatusNotAcceptable) ErrProxyAuthRequired = StatusError(http.StatusProxyAuthRequired) ErrRequestTimeout = StatusError(http.StatusRequestTimeout) ErrConflict = StatusError(http.StatusConflict) ErrGone = StatusError(http.StatusGone) ErrLengthRequired = StatusError(http.StatusLengthRequired) ErrPreconditionFailed = StatusError(http.StatusPreconditionFailed) ErrRequestEntityTooLarge = StatusError(http.StatusRequestEntityTooLarge) ErrRequestURITooLong = StatusError(http.StatusRequestURITooLong) ErrUnsupportedMediaType = StatusError(http.StatusUnsupportedMediaType) ErrRequestedRangeNotSatisfiable = StatusError(http.StatusRequestedRangeNotSatisfiable) ErrExpectationFailed = StatusError(http.StatusExpectationFailed) ErrTeapot = StatusError(http.StatusTeapot) ErrMisdirectedRequest = StatusError(http.StatusMisdirectedRequest) ErrUnprocessableEntity = StatusError(http.StatusUnprocessableEntity) ErrLocked = StatusError(http.StatusLocked) ErrFailedDependency = StatusError(http.StatusFailedDependency) ErrTooEarly = StatusError(http.StatusTooEarly) ErrUpgradeRequired = StatusError(http.StatusUpgradeRequired) ErrPreconditionRequired = StatusError(http.StatusPreconditionRequired) ErrTooManyRequests = StatusError(http.StatusTooManyRequests) ErrRequestHeaderFieldsTooLarge = StatusError(http.StatusRequestHeaderFieldsTooLarge) ErrInternalServerError = StatusError(http.StatusInternalServerError) ErrNotImplemented = StatusError(http.StatusNotImplemented) ErrBadGateway = StatusError(http.StatusBadGateway) ErrGatewayTimeout = StatusError(http.StatusGatewayTimeout) ErrHTTPVersionNotSupported = StatusError(http.StatusHTTPVersionNotSupported) ErrVariantAlsoNegotiates = StatusError(http.StatusVariantAlsoNegotiates) ErrInsufficientStorage = StatusError(http.StatusInsufficientStorage) ErrLoopDetected = StatusError(http.StatusLoopDetected) ErrNotExtended = StatusError(http.StatusNotExtended) ErrNetworkAuthenticationRequired = StatusError(http.StatusNetworkAuthenticationRequired) )
HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
var ( // Get returns a ErrMethodNotAllowed if request method is not a GET. Use with Chain. Get = newMethodChecker(http.MethodGet) // Head returns a ErrMethodNotAllowed if request method is not a HEAD. Use with Chain. Head = newMethodChecker(http.MethodHead) // Post returns a ErrMethodNotAllowed if request method is not a Post. Use with Chain. Post = newMethodChecker(http.MethodPost) // Put returns a ErrMethodNotAllowed if request method is not a Put. Use with Chain. Put = newMethodChecker(http.MethodPut) // Patch returns a ErrMethodNotAllowed if request method is not a Patch. Use with Chain. Patch = newMethodChecker(http.MethodPatch) // Delete returns a ErrMethodNotAllowed if request method is not a Delete. Use with Chain. Delete = newMethodChecker(http.MethodDelete) // Connect returns a ErrMethodNotAllowed if request method is not a Connect. Use with Chain. Connect = newMethodChecker(http.MethodConnect) // Options returns a ErrMethodNotAllowed if request method is not a Options. Use with Chain. Options = newMethodChecker(http.MethodOptions) // Trace returns a ErrMethodNotAllowed if request method is not a Trace. Use with Chain. Trace = newMethodChecker(http.MethodTrace) )
Functions ¶
func NewHandler ¶
NewHandler creates a new http.HandlerFunc which calls HandlerE.ServeHTTP and if it returns an error calls ErrWriter.Write to create the appropriate response.
func NewHandlerFunc ¶
func NewHandlerFunc(h HandlerFuncE, ew ErrWriterFunc) http.HandlerFunc
NewHandlerFunc creates a new http.HandlerFunc which calls HandlerFuncE and if it returns an error calls ErrWriterFunc to create the appropriate response.
func NewSafeHandler ¶ added in v0.0.25
NewSafeHandler creates a new http.HandlerFunc which calls HandlerE.ServeHTTP and if it returns an error calls WriteHTTPeErr to create the appropriate response.
func NewSafeHandlerFunc ¶ added in v0.0.25
func NewSafeHandlerFunc(h HandlerFuncE) http.HandlerFunc
NewSafeHandlerFunc creates a new http.HandlerFunc which calls HandlerFuncE and if it returns an error calls WriteHTTPeErr to create the appropriate response.
func WriteSafeErr ¶ added in v0.0.25
func WriteSafeErr(w http.ResponseWriter, err error)
WriteSafeErr writes the http status represented by err to the ResponseWriter and prints the error message for 4xx errors, but keeps details for 5xx errors. It writes 5xx errors "safely" by it doesn't leak any error details.
Types ¶
type ErrWriter ¶
type ErrWriter interface {
WriteErr(http.ResponseWriter, error)
}
ErrWriter translates an error into the appropriate http response StatusCode and Body and writes it.
type ErrWriterFunc ¶
type ErrWriterFunc func(http.ResponseWriter, error)
The ErrWriterFunc type is an adapter to allow the use of ordinary functions as ErrWriter. If f is a function with the appropriate signature, ErrWriterFunc(f) is a ErrWriter that calls f.
func (ErrWriterFunc) WriteErr ¶
func (ew ErrWriterFunc) WriteErr(w http.ResponseWriter, err error)
WriteErr translates an error into the appropriate http response StatusCode and Body and writes it.
type HandlerE ¶
type HandlerE interface {
ServeHTTPe(http.ResponseWriter, *http.Request) error
}
HandlerE works like an HTTP.Handler with the addition of an error return value. It is intended to be used with ErrWriter which handles the error and turns it into an appropriate http response StatusCode and Body.
type HandlerFuncE ¶
type HandlerFuncE func(http.ResponseWriter, *http.Request) error
The HandlerFuncE type is an adapter to allow the use of ordinary functions as HandlerE. If f is a function with the appropriate signature, HandlerFuncE(f) is a HandlerE that calls f.
Example ¶
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "foxygo.at/s/httpe" ) type User struct { Name string Age int } var ( errInput = errors.New("input error") errDuplicate = errors.New("duplicate") storage = map[string]User{} ) func handle(w http.ResponseWriter, r *http.Request) error { user := User{} body, _ := ioutil.ReadAll(r.Body) if err := json.Unmarshal(body, &user); err != nil { return errInput } if user.Name == "" || user.Age < 0 { return errInput } if _, ok := storage[user.Name]; ok { return errDuplicate } storage[user.Name] = user return nil } func writeErr(w http.ResponseWriter, err error) { switch { case errors.Is(err, errInput): http.Error(w, err.Error(), http.StatusBadRequest) case errors.Is(err, errDuplicate): http.Error(w, "duplicate user", http.StatusForbidden) default: http.Error(w, "something went wrong", http.StatusInternalServerError) } } func main() { handler := httpe.NewHandlerFunc(handle, writeErr) // http.ListenAndServe(":9090", handler) w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/user", strings.NewReader(`{"Name": "truncated...`)) handler(w, r) fmt.Printf("%d %s", w.Code, w.Body.String()) }
Output: 400 input error
func (HandlerFuncE) ServeHTTPe ¶
func (f HandlerFuncE) ServeHTTPe(w http.ResponseWriter, r *http.Request) error
ServeHTTPe calls f(w, r) and returns its error.
type StatusError ¶ added in v0.0.25
type StatusError int
StatusError wraps an http.StatusCode of value 4xx or 5xx. It is used in combination with various sentinel values each representing a http status code for convenience with HandlerE and HandlerFuncE.
func (StatusError) Code ¶ added in v0.0.25
func (err StatusError) Code() int
Code returns a status int representing an http.Status* value.
func (StatusError) Error ¶ added in v0.0.25
func (err StatusError) Error() string
Error returns the error message and implements the error interface.
func (StatusError) IsClientError ¶ added in v0.0.25
func (err StatusError) IsClientError() bool
IsClientError returns true if the error is in 4xx range. Useful for error message printing and hiding details.