traefik/middlewares/headers.go

72 lines
2 KiB
Go
Raw Normal View History

2017-06-13 00:48:21 +00:00
package middlewares
//Middleware based on https://github.com/unrolled/secure
import (
"net/http"
2017-11-08 10:40:04 +00:00
"github.com/containous/traefik/types"
2017-06-13 00:48:21 +00:00
)
// HeaderOptions is a struct for specifying configuration options for the headers middleware.
type HeaderOptions struct {
// If Custom request headers are set, these will be added to the request
CustomRequestHeaders map[string]string
// If Custom response headers are set, these will be added to the ResponseWriter
CustomResponseHeaders map[string]string
}
// HeaderStruct is a middleware that helps setup a few basic security features. A single headerOptions struct can be
// provided to configure which features should be enabled, and the ability to override a few of the default values.
type HeaderStruct struct {
// Customize headers with a headerOptions struct.
opt HeaderOptions
}
// NewHeaderFromStruct constructs a new header instance from supplied frontend header struct.
2018-01-02 09:10:04 +00:00
func NewHeaderFromStruct(headers *types.Headers) *HeaderStruct {
if headers == nil || !headers.HasCustomHeadersDefined() {
return nil
2017-06-13 00:48:21 +00:00
}
return &HeaderStruct{
2018-01-02 09:10:04 +00:00
opt: HeaderOptions{
CustomRequestHeaders: headers.CustomRequestHeaders,
CustomResponseHeaders: headers.CustomResponseHeaders,
},
2017-06-13 00:48:21 +00:00
}
}
func (s *HeaderStruct) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
2017-11-23 16:40:03 +00:00
s.ModifyRequestHeaders(r)
2017-06-13 00:48:21 +00:00
// If there is a next, call it.
if next != nil {
next(w, r)
}
}
2017-11-23 16:40:03 +00:00
// ModifyRequestHeaders set or delete request headers
func (s *HeaderStruct) ModifyRequestHeaders(r *http.Request) {
2017-06-13 00:48:21 +00:00
// Loop through Custom request headers
for header, value := range s.opt.CustomRequestHeaders {
2017-11-23 16:40:03 +00:00
if value == "" {
r.Header.Del(header)
} else {
r.Header.Set(header, value)
}
2017-06-13 00:48:21 +00:00
}
2017-11-23 16:40:03 +00:00
}
2017-06-13 00:48:21 +00:00
2017-11-23 16:40:03 +00:00
// ModifyResponseHeaders set or delete response headers
func (s *HeaderStruct) ModifyResponseHeaders(res *http.Response) error {
2017-06-13 00:48:21 +00:00
// Loop through Custom response headers
for header, value := range s.opt.CustomResponseHeaders {
2017-11-23 16:40:03 +00:00
if value == "" {
res.Header.Del(header)
} else {
res.Header.Set(header, value)
}
2017-06-13 00:48:21 +00:00
}
2017-11-23 16:40:03 +00:00
return nil
2017-06-13 00:48:21 +00:00
}