golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/coordinator/modproxy_test.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build linux || darwin 6 7 package main 8 9 import ( 10 "io" 11 "net/http" 12 "net/http/httptest" 13 "testing" 14 ) 15 16 // TestProxyURL tests that the response served from proxyURL is not a 17 // redirect, even if its backend URL serves a redirect. That is, our 18 // proxy should do the redirect following, not defer that to the 19 // client. 20 func TestProxyURL(t *testing.T) { 21 const content = "some content" 22 const header = "X-Some-Header" 23 tsTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 24 if r.RequestURI == "/bar" { 25 w.Header().Set(header, content) 26 io.WriteString(w, content) 27 } 28 })) 29 defer tsTarget.Close() 30 tsBackend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 31 if r.RequestURI == "/foo" { 32 if v := r.Header.Get(header); v != content { 33 t.Errorf("header(%q) = %q in handler; want %q", header, v, content) 34 w.WriteHeader(400) 35 return 36 } 37 http.Redirect(w, r, tsTarget.URL+"/bar", http.StatusFound) 38 return 39 } 40 w.WriteHeader(400) 41 })) 42 defer tsBackend.Close() 43 44 req := httptest.NewRequest("GET", "/foo", nil) 45 req.Header.Set(header, content) 46 rr := httptest.NewRecorder() 47 proxyURL(rr, req, tsBackend.URL) 48 got := rr.Result() 49 gotBody := rr.Body.String() 50 if got.StatusCode != 200 { 51 t.Errorf("status = %q; want 200", got.StatusCode) 52 } 53 if gotBody != content { 54 t.Errorf("content = %q; want %q", gotBody, content) 55 } 56 if h := got.Header.Get(header); h != content { 57 t.Errorf("header(%q) = %q; want %q", header, h, content) 58 } 59 }