github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/tests/integration/header/header_test.go (about)

     1  // Copyright 2020 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //	https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package header
    16  
    17  import (
    18  	"bufio"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"strings"
    22  	"testing"
    23  
    24  	"github.com/google/go-cmp/cmp"
    25  	"github.com/google/go-safeweb/safehttp"
    26  	"github.com/google/safehtml"
    27  )
    28  
    29  func TestAccessIncomingHeaders(t *testing.T) {
    30  	mb := safehttp.NewServeMuxConfig(nil)
    31  	mux := mb.Mux()
    32  
    33  	mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(func(rw safehttp.ResponseWriter, ir *safehttp.IncomingRequest) safehttp.Result {
    34  		if got, want := ir.Header.Get("A"), "B"; got != want {
    35  			t.Errorf(`ir.Header.Get("A") got: %v want: %v`, got, want)
    36  		}
    37  		return rw.Write(safehtml.HTMLEscaped("hello"))
    38  	}))
    39  
    40  	request := "GET / HTTP/1.1\r\n" +
    41  		"Host: foo.com\r\n" +
    42  		"A: B\r\n\r\n"
    43  	req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(request)))
    44  	if err != nil {
    45  		t.Fatalf("http.ReadRequest() got err: %v", err)
    46  	}
    47  
    48  	rw := httptest.NewRecorder()
    49  	mux.ServeHTTP(rw, req)
    50  }
    51  
    52  func TestChangingResponseHeaders(t *testing.T) {
    53  	mb := safehttp.NewServeMuxConfig(nil)
    54  	mux := mb.Mux()
    55  
    56  	mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(func(rw safehttp.ResponseWriter, ir *safehttp.IncomingRequest) safehttp.Result {
    57  		rw.Header().Set("pIZZA", "Pasta")
    58  		return rw.Write(safehtml.HTMLEscaped("hello"))
    59  	}))
    60  
    61  	req := httptest.NewRequest(safehttp.MethodGet, "http://foo.com/", nil)
    62  	rw := httptest.NewRecorder()
    63  
    64  	mux.ServeHTTP(rw, req)
    65  
    66  	want := []string{"Pasta"}
    67  	if diff := cmp.Diff(want, rw.Header()["Pizza"]); diff != "" {
    68  		t.Errorf(`rw.Header()["Pizza"] mismatch (-want +got):\n%s`, diff)
    69  	}
    70  }