Finish first working version of reqlog

This commit is contained in:
David Stotijn
2020-09-19 01:27:55 +02:00
parent c5cf6ef867
commit 211c11be2b
10 changed files with 646 additions and 280 deletions

View File

@ -10,8 +10,14 @@ import (
"net"
"net/http"
"net/http/httputil"
"github.com/google/uuid"
)
type contextKey int
const ReqIDKey contextKey = 0
// Proxy implements http.Handler and offers MITM behaviour for modifying
// HTTP requests and responses.
type Proxy struct {
@ -46,6 +52,11 @@ func NewProxy(ca *x509.Certificate, key crypto.PrivateKey) (*Proxy, error) {
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Add a unique request ID, to be used for correlating responses to requests.
reqID := uuid.New()
ctx := context.WithValue(r.Context(), ReqIDKey, reqID)
r = r.WithContext(ctx)
if r.Method == http.MethodConnect {
p.handleConnect(w, r)
return
@ -69,6 +80,10 @@ func (p *Proxy) modifyRequest(r *http.Request) {
r.URL.Scheme = "https"
}
// Setting `X-Forwarded-For` to `nil` ensures that http.ReverseProxy doesn't
// set this header.
r.Header["X-Forwarded-For"] = nil
fn := nopReqModifier
for i := len(p.reqModifiers) - 1; i >= 0; i-- {
@ -119,7 +134,7 @@ func (p *Proxy) handleConnect(w http.ResponseWriter, r *http.Request) {
l := &OnceAcceptListener{clientConnNotify.Conn}
err = http.Serve(l, p.handler)
err = http.Serve(l, p)
if err != nil && err != ErrAlreadyAccepted {
log.Printf("[ERROR] Serving HTTP request failed: %v", err)
}