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-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-01-30 13:46:09 +08:00
|
|
|
Next http.HandlerFunc
|
|
|
|
Rules []HeaderRule
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP implements the http.Handler interface and serves the requests,
|
|
|
|
// adding headers to the response according to the configured rules.
|
2015-01-30 13:46:09 +08:00
|
|
|
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
for _, rule := range h.Rules {
|
2015-01-30 13:08:40 +08:00
|
|
|
if middleware.Path(r.URL.Path).Matches(rule.Url) {
|
2015-01-30 13:05:05 +08:00
|
|
|
for _, header := range rule.Headers {
|
|
|
|
w.Header().Set(header.Name, header.Value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-01-30 13:46:09 +08:00
|
|
|
h.Next(w, r)
|
2015-01-30 13:05:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type (
|
2015-01-30 13:46:09 +08:00
|
|
|
// HeaderRule groups a slice of HTTP headers by a URL pattern.
|
2015-01-30 13:05:05 +08:00
|
|
|
// TODO: use http.Header type instead??
|
2015-01-30 13:46:09 +08:00
|
|
|
HeaderRule struct {
|
2015-01-30 13:05:05 +08:00
|
|
|
Url 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
|
|
|
|
}
|
|
|
|
)
|