github.com/blend/go-sdk@v1.20240719.1/reverseproxy/redirect_http_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package reverseproxy
     9  
    10  import (
    11  	"fmt"
    12  	"io"
    13  	"net/http"
    14  	"net/http/httptest"
    15  	"strings"
    16  	"testing"
    17  
    18  	"github.com/blend/go-sdk/assert"
    19  )
    20  
    21  func TestRedirectHost(t *testing.T) {
    22  	assert := assert.New(t)
    23  
    24  	redirect := HTTPRedirect{
    25  		RedirectScheme: "spdy",
    26  		RedirectHost:   "redirect-host",
    27  	}
    28  	mockedRedirect := httptest.NewServer(redirect)
    29  
    30  	client := &http.Client{
    31  		CheckRedirect: func(req *http.Request, via []*http.Request) error {
    32  			return http.ErrUseLastResponse
    33  		},
    34  	}
    35  
    36  	url := fmt.Sprintf("%s/foo", mockedRedirect.URL)
    37  	res, err := client.Get(url)
    38  	assert.Nil(err)
    39  	defer res.Body.Close()
    40  
    41  	fullBody, err := io.ReadAll(res.Body)
    42  	assert.Nil(err)
    43  
    44  	mockedContents := string(fullBody)
    45  	assert.Equal(http.StatusMovedPermanently, res.StatusCode)
    46  
    47  	assert.Contains(mockedContents, "spdy://redirect-host/foo")
    48  }
    49  
    50  func TestRedirect(t *testing.T) {
    51  	assert := assert.New(t)
    52  
    53  	var redirect HTTPRedirect
    54  	mockedRedirect := httptest.NewServer(redirect)
    55  
    56  	client := &http.Client{
    57  		CheckRedirect: func(req *http.Request, via []*http.Request) error {
    58  			return http.ErrUseLastResponse
    59  		},
    60  	}
    61  
    62  	urlSuffixes := []string{
    63  		"foo/bar",
    64  		"foo/bar/",
    65  		"foo/bar?test=me",
    66  	}
    67  
    68  	for _, urlSuffix := range urlSuffixes {
    69  		url := fmt.Sprintf("%s/%s", mockedRedirect.URL, urlSuffix)
    70  		res, err := client.Get(url)
    71  		assert.Nil(err)
    72  		defer res.Body.Close()
    73  
    74  		fullBody, err := io.ReadAll(res.Body)
    75  		assert.Nil(err)
    76  
    77  		mockedContents := string(fullBody)
    78  		assert.Equal(http.StatusMovedPermanently, res.StatusCode)
    79  
    80  		expectedURL := strings.Replace(url, "http", "https", -1)
    81  		assert.Contains(mockedContents, expectedURL)
    82  	}
    83  }