2015-01-30 01:52:18 -05: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 00:05:05 -05:00
|
|
|
package headers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2015-05-08 10:43:32 -05:00
|
|
|
"strings"
|
2015-01-30 00:05:05 -05:00
|
|
|
|
2015-01-30 00:08:40 -05:00
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-30 00:05:05 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Headers is middleware that adds headers to the responses
|
|
|
|
// for requests matching a certain path.
|
|
|
|
type Headers struct {
|
2015-04-03 00:30:54 -05:00
|
|
|
Next middleware.Handler
|
2015-05-04 07:53:54 -05:00
|
|
|
Rules []Rule
|
2015-01-30 00:05:05 -05:00
|
|
|
}
|
|
|
|
|
2015-03-28 17:48:31 -05:00
|
|
|
// ServeHTTP implements the middleware.Handler interface and serves requests,
|
2015-01-30 00:05:05 -05:00
|
|
|
// adding headers to the response according to the configured rules.
|
2015-03-28 17:48:31 -05:00
|
|
|
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
2015-01-30 00:46:09 -05:00
|
|
|
for _, rule := range h.Rules {
|
2015-01-30 00:08:40 -05:00
|
|
|
if middleware.Path(r.URL.Path).Matches(rule.Url) {
|
2015-01-30 00:05:05 -05:00
|
|
|
for _, header := range rule.Headers {
|
2015-05-08 10:43:32 -05:00
|
|
|
if strings.HasPrefix(header.Name, "-") {
|
|
|
|
w.Header().Del(strings.TrimLeft(header.Name, "-"))
|
|
|
|
} else {
|
|
|
|
w.Header().Set(header.Name, header.Value)
|
|
|
|
}
|
2015-01-30 00:05:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-04-03 00:30:54 -05:00
|
|
|
return h.Next.ServeHTTP(w, r)
|
2015-01-30 00:05:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type (
|
2015-05-04 07:53:54 -05:00
|
|
|
// Rule groups a slice of HTTP headers by a URL pattern.
|
2015-03-28 17:48:31 -05:00
|
|
|
// TODO: use http.Header type instead?
|
2015-05-04 07:53:54 -05:00
|
|
|
Rule struct {
|
2015-01-30 00:05:05 -05:00
|
|
|
Url string
|
2015-01-30 00:46:09 -05:00
|
|
|
Headers []Header
|
2015-01-30 00:05:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Header represents a single HTTP header, simply a name and value.
|
2015-01-30 00:46:09 -05:00
|
|
|
Header struct {
|
2015-01-30 00:05:05 -05:00
|
|
|
Name string
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
)
|