Documentation ¶
Overview ¶
Package handlers implements a number of useful HTTP middlewares.
The general format of the middlewares in this package is to wrap an existing http.Handler in another one. So if you have a ServeMux, you can simply do:
mux := http.NewServeMux() h := handlers.Log(handlers.Debug(mux)) http.ListenAndServe(":5050", h)
And wrap as many handlers as you'd like using that idiom.
Example ¶
package main import ( "fmt" "net/http" "net/http/httptest" "github.com/kevinburke/handlers" ) func main() { mux := http.NewServeMux() h := handlers.Duration(handlers.Server(mux, "custom-server")) req := httptest.NewRequest("GET", "/", nil) w := httptest.NewRecorder() h.ServeHTTP(w, req) fmt.Println(w.Header().Get("Server")) }
Output: custom-server
Index ¶
- Constants
- Variables
- func All(h http.Handler, serverName string) http.Handler
- func AppendLog(r *http.Request, logctx ...interface{})
- func BasicAuth(h http.Handler, realm string, users map[string]string) http.Handler
- func Debug(h http.Handler) http.Handler
- func DebugWriter(h http.Handler, output io.Writer) http.Handler
- func Duration(h http.Handler) http.Handler
- func GZip(h http.Handler) http.Handler
- func GetDuration(ctx context.Context) time.Duration
- func GetRequestID(ctx context.Context) (uuid.UUID, bool)
- func GetStartTime(ctx context.Context) time.Time
- func JSON(h http.Handler) http.Handler
- func Log(h http.Handler) http.Handler
- func NewLogger() *slog.Logger
- func NewLoggerLevel(lvl slog.Level) *slog.Logger
- func RedirectProto(h http.Handler) http.Handler
- func STS(h http.Handler) http.Handler
- func Server(h http.Handler, serverName string) http.Handler
- func SetRequestID(r *http.Request, u uuid.UUID) *http.Request
- func TrailingSlashRedirect(h http.Handler) http.Handler
- func UUID(h http.Handler) http.Handler
- func WithLogger(h http.Handler, logger *slog.Logger) http.Handler
- func WithTimeout(h http.Handler, timeout time.Duration) http.Handler
- type Regexp
- func (h *Regexp) Handle(pattern *regexp.Regexp, methods []string, handler http.Handler)
- func (h *Regexp) HandleFunc(pattern *regexp.Regexp, methods []string, ...)
- func (h *Regexp) HandleString(s string, methods []string, handler http.Handler)
- func (h *Regexp) HandleStringFunc(s string, methods []string, handler func(http.ResponseWriter, *http.Request))
- func (h *Regexp) ServeHTTP(w http.ResponseWriter, r *http.Request)
Examples ¶
Constants ¶
const Version = "0.46"
Variables ¶
var Logger *slog.Logger
Functions ¶
func AppendLog ¶
Append will append the logctx arguments to the log line for this request. The logctx arguments should come in pairs and match those provided to a log15.Logger.
func BasicAuth ¶
BasicAuth protects all requests to the given handler, unless the request has basic auth with a username and password in the users map.
func Debug ¶
Debug prints debugging information about the request to stderr if the DEBUG_HTTP_TRAFFIC environment variable is set to "true".
func DebugWriter ¶
Debug prints debugging information about the request to output if the DEBUG_HTTP_TRAFFIC environment variable is set to "true".
func Duration ¶
Duration sets the start time in the context and sets a X-Request-Duration header on the response, from the time this handler started executing to the time of the first WriteHeader() or Write() call.
func GZip ¶
GZip gzip compresses HTTP responses for clients that support it via the 'Accept-Encoding' header.
Compressing TLS traffic may leak the page contents to an attacker if the page contains user input, known as the CRIME/BEAST attacks: http://security.stackexchange.com/a/102015/12208. Only use the GZip handler with unencrypted traffic, static pages, or pages that only contain public data.
func GetDuration ¶
GetDuration returns the amount of time since the Duration handler ran, or 0 if no Duration was set for this context.
func GetRequestID ¶
GetRequestID returns a UUID (if it exists in the context) or false if none could be found.
func GetStartTime ¶
GetStartTime returns the time the Duration handler ran.
func Log ¶
Log serves the http request and writes information about the request/response using the default Logger (handlers.Logger). Any errors writing to the Logger are ignored.
func NewLogger ¶
NewLogger returns a new customizable Logger, with the same initial settings as the package Logger. Compared with a default log15.Logger, the 40-char spacing gap between the message and the first key is omitted, and timestamps are written with more precision.
func NewLoggerLevel ¶
NewLoggerLevel returns a Logger with our customized settings, set to log messages at or more critical than the given level.
func RedirectProto ¶
RedirectProto redirects requests with an "X-Forwarded-Proto: http" header to their HTTPS equivalent.
func SetRequestID ¶
SetRequestID sets the given UUID on the request context and returns the modified HTTP request.
func TrailingSlashRedirect ¶
TrailingSlashRedirect redirects any path that ends with a "/" - say, "/messages/" - to the stripped version, say "/messages".
func UUID ¶
UUID attaches a X-Request-Id header to the request, and sets one on the request context, unless one already exists.
func WithLogger ¶
WithLogger logs information about HTTP requests and responses to the provided Logger, including a detailed timestamp, the user agent, the response time, the number of bytes written, and more. Any errors writing log information to the Logger are ignored.
Types ¶
type Regexp ¶
type Regexp struct {
// contains filtered or unexported fields
}
A RegexpHandler is a simple http.Handler that can match regular expressions for routes.
Example ¶
package main import ( "io" "net/http" "regexp" "github.com/kevinburke/handlers" ) func main() { // GET /v1/jobs/:job-name route := regexp.MustCompile(`^/v1/jobs/(?P<JobName>[^\s\/]+)$`) h := new(handlers.Regexp) h.HandleFunc(route, []string{"GET", "POST"}, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello World!") }) }
Output:
func (*Regexp) Handle ¶
Handle calls the provided handler for requests whose URL matches the given pattern and HTTP method. The first matching route will get called. If methods is nil, all HTTP methods will be allowed. If GET is in the list of methods, HEAD requests will also be allowed.
func (*Regexp) HandleFunc ¶
func (h *Regexp) HandleFunc(pattern *regexp.Regexp, methods []string, handler func(http.ResponseWriter, *http.Request))
HandleFunc calls the provided HandlerFunc for requests whose URL matches the given pattern and HTTP method. The first matching route will get called. If methods is nil, all HTTP methods are allowed. If GET is in the list of methods, HEAD requests will also be allowed.
func (*Regexp) HandleString ¶
HandleString is like Handle, but will compile s to a regexp first. If s is not a valid regexp HandleString will panic.
func (*Regexp) HandleStringFunc ¶
func (h *Regexp) HandleStringFunc(s string, methods []string, handler func(http.ResponseWriter, *http.Request))
HandleStringFunc is like HandleFunc, but will compile s to a regexp first. If s is not a valid regexp HandleStringFunc will panic.