Skip to content

Commit

Permalink
middleware: add Logger.WrapRoundTripper
Browse files Browse the repository at this point in the history
  • Loading branch information
mmatczuk committed Dec 12, 2023
1 parent e95928a commit 14b3829
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"github.com/saucelabs/forwarder/internal/martian"
"github.com/saucelabs/forwarder/utils/httpx"
)

type LogEntry struct {
Expand All @@ -20,6 +21,18 @@ type LogEntry struct {
Duration time.Duration
}

func makeLogEntry(req *http.Request, res *http.Response, d time.Duration) LogEntry {
le := LogEntry{
Request: req,
Response: res,
Duration: d,
}
if res != nil {
le.Status = res.StatusCode
}
return le
}

type Logger func(e LogEntry)

func (l Logger) Wrap(h http.Handler) http.Handler {
Expand All @@ -38,6 +51,15 @@ func (l Logger) Wrap(h http.Handler) http.Handler {
})
}

func (l Logger) WrapRoundTripper(rt http.RoundTripper) http.RoundTripper {
return httpx.RoundTripperFunc(func(req *http.Request) (res *http.Response, err error) {
start := time.Now()
res, err = rt.RoundTrip(req)
l(makeLogEntry(req, res, time.Since(start)))
return
})
}

const startTimeKey = "start-time"

func (l Logger) ModifyRequest(req *http.Request) error {
Expand All @@ -55,13 +77,7 @@ func (l Logger) ModifyResponse(res *http.Response) error {
d = time.Since(ss)
}
}

l(LogEntry{
Request: res.Request,
Response: res,
Status: res.StatusCode,
Duration: d,
})
l(makeLogEntry(res.Request, res, d))

return nil
}

0 comments on commit 14b3829

Please sign in to comment.