80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"testing"
|
|
)
|
|
|
|
func TestReverseProxyPathRewrite(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/v1/health" {
|
|
t.Fatalf("path %q", r.URL.Path)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer srv.Close()
|
|
up, _ := url.Parse(srv.URL)
|
|
rp := NewReverseProxy(up, "/api/main_srv", "/v1", "")
|
|
// Client-style request (no RequestURI / server quirks from httptest.NewRequest).
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/api/main_srv/health", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
rp.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status %d", rec.Code)
|
|
}
|
|
}
|
|
|
|
func TestReverseProxyPathRewriteWithAPIBasePath(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/api/v1/health" {
|
|
t.Fatalf("path %q", r.URL.Path)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer srv.Close()
|
|
up, err := url.Parse(srv.URL + "/api/")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rp := NewReverseProxy(up, "/api/main_srv", "/v1", "")
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/api/main_srv/health", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
rp.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status %d", rec.Code)
|
|
}
|
|
}
|
|
|
|
func TestReverseProxyPathNestedStatsUsers(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/api/v1/stats/users" {
|
|
t.Fatalf("path %q", r.URL.Path)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer srv.Close()
|
|
up, err := url.Parse(srv.URL + "/api/")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rp := NewReverseProxy(up, "/api/gt2", "/v1", "")
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/api/gt2/stats/users", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
rp.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status %d", rec.Code)
|
|
}
|
|
}
|