Skip to content

Commit

Permalink
With response (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
jssblck authored Feb 16, 2024
1 parent 2740e13 commit 7ca328f
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,19 @@ import (
"net/http"
"net/http/httputil"
"net/url"
"unicode/utf8"
)

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)
Expand Down Expand Up @@ -67,12 +70,40 @@ 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)

if printResponse {
rr := responseRecorder{w}
proxy.ServeHTTP(rr, r)
} else {
proxy.ServeHTTP(w, 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("<binary content>\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)
}

0 comments on commit 7ca328f

Please sign in to comment.