Flatten HTTP handler config (#2662)

Differentiating middleware and responders has one benefit, namely that
it's clear which module provides the response, but even then it's not
a great advantage. Linear handler config makes a little more sense,
giving greater flexibility and simplifying the core a bit, even though
it's slightly awkward that handlers which are responders may not use
the 'next' handler that is passed in at all.
This commit is contained in:
Matthew Holt
2019-07-09 12:58:39 -06:00
parent 6dfba5fda8
commit 4a3a418156
9 changed files with 99 additions and 148 deletions

View File

@@ -24,21 +24,20 @@ import (
func init() {
caddy.RegisterModule(caddy.Module{
Name: "http.responders.static",
Name: "http.handlers.static",
New: func() interface{} { return new(Static) },
})
}
// Static implements a simple responder for static responses.
type Static struct {
StatusCode int `json:"status_code"` // TODO: should we turn this into a string so that only one field is needed? (string allows replacements)
StatusCodeStr string `json:"status_code_str"`
Headers http.Header `json:"headers"`
Body string `json:"body"`
Close bool `json:"close"`
StatusCode string `json:"status_code"`
Headers http.Header `json:"headers"`
Body string `json:"body"`
Close bool `json:"close"`
}
func (s Static) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
func (s Static) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(caddy.Replacer)
// close the connection after responding
@@ -60,16 +59,13 @@ func (s Static) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
}
// get the status code
statusCode := s.StatusCode
if statusCode == 0 && s.StatusCodeStr != "" {
intVal, err := strconv.Atoi(repl.ReplaceAll(s.StatusCodeStr, ""))
statusCode := http.StatusOK
if s.StatusCode != "" {
intVal, err := strconv.Atoi(repl.ReplaceAll(s.StatusCode, ""))
if err == nil {
statusCode = intVal
}
}
if statusCode == 0 {
statusCode = http.StatusOK
}
// write headers
w.WriteHeader(statusCode)
@@ -83,4 +79,4 @@ func (s Static) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
}
// Interface guard
var _ Handler = (*Static)(nil)
var _ MiddlewareHandler = (*Static)(nil)