httputil : wrap handlers for additional context (#413)

Signed-off-by: Bobby DeSimone <bobbydesimone@gmail.com>
This commit is contained in:
Bobby DeSimone 2019-12-06 11:07:45 -08:00 committed by GitHub
parent 487fc655d6
commit b3d3159185
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 495 additions and 463 deletions

View file

@ -1,6 +1,8 @@
package httputil // import "github.com/pomerium/pomerium/internal/httputil"
import (
"errors"
"fmt"
"net/http"
)
@ -14,7 +16,7 @@ func HealthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodGet {
w.Write([]byte(http.StatusText(http.StatusOK)))
fmt.Fprintln(w, http.StatusText(http.StatusOK))
}
}
@ -24,3 +26,22 @@ func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) {
w.Header().Set(HeaderPomeriumResponse, "true")
http.Redirect(w, r, url, code)
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
//
// adapted from std library to suppport error wrapping
type HandlerFunc func(http.ResponseWriter, *http.Request) error
// ServeHTTP calls f(w, r) error.
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
var e *HTTPError
if !errors.As(err, &e) {
e = &HTTPError{http.StatusInternalServerError, err}
}
e.ErrorResponse(w, r)
}
}