From a262a94a3528749abcce254a6860e7e28eafe393 Mon Sep 17 00:00:00 2001 From: Jessica Black Date: Mon, 22 Jan 2024 14:55:33 -0800 Subject: [PATCH 1/2] Write responses --- main.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 79a8d2a..c549cfb 100644 --- a/main.go +++ b/main.go @@ -14,6 +14,7 @@ import ( "net/http" "net/http/httputil" "net/url" + "unicode/utf8" ) var proxyTarget string @@ -67,12 +68,36 @@ func main() { // Replace the body in the request with a new reader that just reads from the body // that was previously buffered at the start of this function, and perform the reverse proxy. r.Body = ioutil.NopCloser(bytes.NewBuffer(body)) - proxy.ServeHTTP(w, r) + + rr := responseRecorder{w} + proxy.ServeHTTP(rr, r) }) http.ListenAndServe(listen, nil) } +type responseRecorder struct { + w http.ResponseWriter +} + +func (rr responseRecorder) Header() http.Header { + return rr.w.Header() +} + +func (rr responseRecorder) Write(content []byte) (int, error) { + if !utf8.Valid(content) { + log.Printf("\n") + } else { + log.Printf("%s\n", content) + } + return rr.w.Write(content) +} + +func (rr responseRecorder) WriteHeader(status int) { + log.Printf("✨ Response:\n%v\n", status) + rr.w.WriteHeader(status) +} + func bailf(msg string, err error) { log.Fatalf("😵 error: "+msg, err) } From f77df84e4e73ea370f7d9955c7be490412de67db Mon Sep 17 00:00:00 2001 From: Jessica Black Date: Fri, 16 Feb 2024 10:22:26 -0800 Subject: [PATCH 2/2] make printing response optional --- main.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index c549cfb..5861845 100644 --- a/main.go +++ b/main.go @@ -19,12 +19,14 @@ import ( var proxyTarget string var listen string +var printResponse bool func main() { log.SetFlags(0) flag.StringVar(&proxyTarget, "proxy", "https://app.fossa.com", "The host to which all requests should be proxied.") flag.StringVar(&listen, "listen", ":3000", "The local address on which to listen.") + flag.BoolVar(&printResponse, "response", false, "Prints the response from the remote endpoint if enabled and if the response is text.") flag.Parse() proxyUrl, err := url.Parse(proxyTarget) @@ -69,8 +71,12 @@ func main() { // that was previously buffered at the start of this function, and perform the reverse proxy. r.Body = ioutil.NopCloser(bytes.NewBuffer(body)) - rr := responseRecorder{w} - proxy.ServeHTTP(rr, r) + if printResponse { + rr := responseRecorder{w} + proxy.ServeHTTP(rr, r) + } else { + proxy.ServeHTTP(w, r) + } }) http.ListenAndServe(listen, nil)