Created
July 4, 2020 12:20
-
-
Save SyureNyanko/1a6a71079f19cfc41a75de8013d4c3a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httptest" | |
"net/http/httputil" | |
"net/url" | |
"os/exec" | |
"strings" | |
) | |
func awsS3(endpoint string) { | |
log.Println(endpoint) | |
out, err := exec.Command("aws", "--endpoint-url", endpoint, "s3", "ls", "s3://test").Output() | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(string(out)) | |
} | |
func singleJoiningSlash(a, b string) string { | |
aslash := strings.HasSuffix(a, "/") | |
bslash := strings.HasPrefix(b, "/") | |
switch { | |
case aslash && bslash: | |
return a + b[1:] | |
case !aslash && !bslash: | |
return a + "/" + b | |
} | |
return a + b | |
} | |
func NewDefaultReverseProxy(target *url.URL) *httputil.ReverseProxy { | |
targetQuery := target.RawQuery | |
director := func(req *http.Request) { | |
req.URL.Scheme = target.Scheme | |
req.URL.Host = target.Host | |
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path) | |
if targetQuery == "" || req.URL.RawQuery == "" { | |
req.URL.RawQuery = targetQuery + req.URL.RawQuery | |
} else { | |
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery | |
} | |
if _, ok := req.Header["User-Agent"]; !ok { | |
// explicitly disable User-Agent so it's not set to default value | |
req.Header.Set("User-Agent", "") | |
} | |
log.Printf("proxy request %+v", req.URL) | |
} | |
return &httputil.ReverseProxy{Director: director} | |
} | |
func main() { | |
backendURL := "http://127.0.0.1:9000" | |
rpURL, err := url.Parse(backendURL) | |
if err != nil { | |
fmt.Println("parse error", backendURL) | |
} | |
frontendProxy := httptest.NewServer(NewDefaultReverseProxy(rpURL)) | |
defer frontendProxy.Close() | |
awsS3(frontendProxy.URL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment