Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

With response #1

Merged
merged 2 commits into from
Feb 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading