github.com/thanos-io/thanos@v0.32.5/test/e2e/e2ethanos/helpers.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package e2ethanos
     5  
     6  import (
     7  	"net/http"
     8  	"net/http/httputil"
     9  	"net/url"
    10  	"os/exec"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/efficientgo/e2e"
    15  
    16  	"github.com/efficientgo/core/testutil"
    17  )
    18  
    19  func CleanScenario(t testing.TB, e *e2e.DockerEnvironment) func() {
    20  	return func() {
    21  		// Make sure Clean can properly delete everything.
    22  		testutil.Ok(t, exec.Command("chmod", "-R", "777", e.SharedDir()).Run())
    23  		e.Close()
    24  	}
    25  }
    26  
    27  func singleJoiningSlash(a, b string) string {
    28  	aslash := strings.HasSuffix(a, "/")
    29  	bslash := strings.HasPrefix(b, "/")
    30  	switch {
    31  	case aslash && bslash:
    32  		return a + b[1:]
    33  	case !aslash && !bslash:
    34  		return a + "/" + b
    35  	}
    36  	return a + b
    37  }
    38  
    39  // NewSingleHostReverseProxy is almost same as httputil.NewSingleHostReverseProxy
    40  // but it performs a url path rewrite.
    41  func NewSingleHostReverseProxy(target *url.URL, externalPrefix string) *httputil.ReverseProxy {
    42  	targetQuery := target.RawQuery
    43  	director := func(req *http.Request) {
    44  		req.URL.Scheme = target.Scheme
    45  		req.URL.Host = target.Host
    46  		req.URL.Path = singleJoiningSlash(target.Path, strings.TrimPrefix(req.URL.Path, "/"+externalPrefix))
    47  
    48  		if targetQuery == "" || req.URL.RawQuery == "" {
    49  			req.URL.RawQuery = targetQuery + req.URL.RawQuery
    50  		} else {
    51  			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
    52  		}
    53  	}
    54  	return &httputil.ReverseProxy{Director: director}
    55  }