2015-01-30 14:52:18 +08:00
|
|
|
// Package headers provides middleware that appends headers to
|
|
|
|
// requests based on a set of configuration rules that define
|
|
|
|
// which routes receive which headers.
|
2015-01-30 13:05:05 +08:00
|
|
|
package headers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2015-05-08 23:43:32 +08:00
|
|
|
"strings"
|
2015-01-30 13:05:05 +08:00
|
|
|
|
2015-01-30 13:08:40 +08:00
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-30 13:05:05 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Headers is middleware that adds headers to the responses
|
|
|
|
// for requests matching a certain path.
|
|
|
|
type Headers struct {
|
2015-04-03 13:30:54 +08:00
|
|
|
Next middleware.Handler
|
2015-05-04 20:53:54 +08:00
|
|
|
Rules []Rule
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
|
2015-03-29 06:48:31 +08:00
|
|
|
// ServeHTTP implements the middleware.Handler interface and serves requests,
|
2015-05-10 03:45:28 +08:00
|
|
|
// setting headers on the response according to the configured rules.
|
2015-03-29 06:48:31 +08:00
|
|
|
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
2015-01-30 13:46:09 +08:00
|
|
|
for _, rule := range h.Rules {
|
2015-05-10 03:45:28 +08:00
|
|
|
if middleware.Path(r.URL.Path).Matches(rule.Path) {
|
2015-01-30 13:05:05 +08:00
|
|
|
for _, header := range rule.Headers {
|
2015-05-08 23:43:32 +08:00
|
|
|
if strings.HasPrefix(header.Name, "-") {
|
|
|
|
w.Header().Del(strings.TrimLeft(header.Name, "-"))
|
|
|
|
} else {
|
|
|
|
w.Header().Set(header.Name, header.Value)
|
|
|
|
}
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-04-03 13:30:54 +08:00
|
|
|
return h.Next.ServeHTTP(w, r)
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type (
|
2015-05-04 20:53:54 +08:00
|
|
|
// Rule groups a slice of HTTP headers by a URL pattern.
|
2015-03-29 06:48:31 +08:00
|
|
|
// TODO: use http.Header type instead?
|
2015-05-04 20:53:54 +08:00
|
|
|
Rule struct {
|
2015-05-10 03:45:28 +08:00
|
|
|
Path string
|
2015-01-30 13:46:09 +08:00
|
|
|
Headers []Header
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Header represents a single HTTP header, simply a name and value.
|
2015-01-30 13:46:09 +08:00
|
|
|
Header struct {
|
2015-01-30 13:05:05 +08:00
|
|
|
Name string
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
)
|