0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00

Allow multiple values for an HTTP header and

add a test to ensure this works.
This commit is contained in:
Garrett Squire 2016-07-20 14:23:55 -07:00
parent beae16f07c
commit e7c842215e
2 changed files with 36 additions and 0 deletions

View file

@ -24,8 +24,12 @@ func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)
for _, rule := range h.Rules { for _, rule := range h.Rules {
if httpserver.Path(r.URL.Path).Matches(rule.Path) { if httpserver.Path(r.URL.Path).Matches(rule.Path) {
for _, header := range rule.Headers { for _, header := range rule.Headers {
// One can either delete a header, add multiple values to a header, or simply
// set a header.
if strings.HasPrefix(header.Name, "-") { if strings.HasPrefix(header.Name, "-") {
w.Header().Del(strings.TrimLeft(header.Name, "-")) w.Header().Del(strings.TrimLeft(header.Name, "-"))
} else if strings.HasPrefix(header.Name, "+") {
w.Header().Add(strings.TrimLeft(header.Name, "+"), replacer.Replace(header.Value))
} else { } else {
w.Header().Set(header.Name, replacer.Replace(header.Value)) w.Header().Set(header.Name, replacer.Replace(header.Value))
} }

View file

@ -4,6 +4,8 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
"reflect"
"sort"
"testing" "testing"
"github.com/mholt/caddy/caddyhttp/httpserver" "github.com/mholt/caddy/caddyhttp/httpserver"
@ -55,3 +57,33 @@ func TestHeader(t *testing.T) {
} }
} }
} }
func TestMultipleHeaders(t *testing.T) {
he := Headers{
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 0, nil
}),
Rules: []Rule{
{Path: "/a", Headers: []Header{
{Name: "+Link", Value: "</images/image.png>; rel=preload"},
{Name: "+Link", Value: "</css/main.css>; rel=preload"},
}},
},
}
req, err := http.NewRequest("GET", "/a", nil)
if err != nil {
t.Fatalf("Could not create HTTP request: %v", err)
}
rec := httptest.NewRecorder()
he.ServeHTTP(rec, req)
desiredHeaders := []string{"</css/main.css>; rel=preload", "</images/image.png>; rel=preload"}
actualHeaders := rec.HeaderMap[http.CanonicalHeaderKey("Link")]
sort.Strings(actualHeaders)
if !reflect.DeepEqual(desiredHeaders, actualHeaders) {
t.Errorf("Expected header to contain: %v but got: %v", desiredHeaders, actualHeaders)
}
}