github.com/kubeshop/testkube@v1.17.23/cmd/proxy/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"net/http"
     9  	"net/http/httputil"
    10  	"net/url"
    11  	"os"
    12  	"strings"
    13  )
    14  
    15  var port = flag.Int("port", 8080, "HTTP Proxy port")
    16  var apiPort = flag.Int("apiPort", 8088, "HTTP API port")
    17  var namespace = flag.String("namespace", "testkube", "Testkube installation namespace")
    18  
    19  func init() {
    20  	flag.Parse()
    21  }
    22  
    23  func main() {
    24  	fmt.Printf("Serve on :%d ==> ", *port)
    25  	fmt.Printf("Proxy to :%d\n", *apiPort)
    26  	fmt.Printf("Testkube installed in Kubernetes namespace: %s\n\n", *namespace)
    27  
    28  	http.HandleFunc("/", proxyPass)
    29  	panic(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
    30  }
    31  
    32  type DebugTransport struct{}
    33  
    34  func (DebugTransport) RoundTrip(r *http.Request) (*http.Response, error) {
    35  	b, err := httputil.DumpRequestOut(r, false)
    36  	if err != nil {
    37  		fmt.Printf("error: %+v\n", err)
    38  		return nil, err
    39  	}
    40  	fmt.Println(string(b))
    41  
    42  	return http.DefaultTransport.RoundTrip(r)
    43  }
    44  
    45  func proxyPass(res http.ResponseWriter, req *http.Request) {
    46  	fmt.Printf("\n-------------\n")
    47  	body, _ := io.ReadAll(req.Body)
    48  	fmt.Printf("%s\n", body)
    49  
    50  	prefix := fmt.Sprintf("/api/v1/namespaces/%s/services/testkube-api-server:%d/proxy", *namespace, *apiPort)
    51  	req.URL.Path = strings.Replace(req.URL.Path, prefix, "", -1)
    52  
    53  	newReq := req.Clone(req.Context())
    54  	newReq.Body = io.NopCloser(bytes.NewReader(body))
    55  
    56  	url, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", *apiPort))
    57  	proxy := httputil.NewSingleHostReverseProxy(url)
    58  	if _, ok := os.LookupEnv("DEBUG"); ok {
    59  		proxy.Transport = DebugTransport{}
    60  	}
    61  
    62  	proxy.ServeHTTP(res, newReq)
    63  }