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

Default logger middleware #33

Merged
merged 28 commits into from
Jun 27, 2024
Merged

Conversation

tigerwill90
Copy link
Owner

@tigerwill90 tigerwill90 commented Jun 23, 2024

This PR add a default middleware for logging incoming requests, responses status, and other relevant information. The middleware is compatible with the new slog.Logger and allow to use any handler that implement slog.Handler.

f := fox.New(
    fox.DefaultOptions(),
    fox.WithRedirectTrailingSlash(true),
)

image

It feature also preliminary work for "real" client IP derivation. The WithClientIPStrategy option allows you to set up strategies to derive the client IP address based on your use case and network topology. A sets of builtin strategy are available in the sub-package github.com/tigerwill90/fox/strategy. Any strategy that implement ClientIPStrategy can be integrated to fox.

// ClientIPStrategy define a strategy for obtaining the "real" client IP from HTTP requests. The strategy used must be
// chosen and tuned for your network configuration. This should result in the strategy never returning an error
// i.e., never failing to find a candidate for the "real" IP. Consequently, getting an error result should be treated as
// an application error, perhaps even worthy of panicking. Builtin best practices strategies can be found in the
// github.com/tigerwill90/fox/strategy package. See https://adam-p.ca/blog/2022/03/x-forwarded-for/ for more details on
// how to choose the right strategy for your use-case and network.
type ClientIPStrategy interface {
	// ClientIP returns the "real" client IP according to the implemented strategy. It returns an error if no valid IP
	// address can be derived using the strategy. This is typically considered a misconfiguration error, unless the strategy
	// involves obtaining an untrustworthy or optional value.
	ClientIP(c Context) (*net.IPAddr, error)
}

And now Context.ClientIP will derive the ip using the "rightmost non private" strategy.

f := fox.New(
    fox.DefaultOptions(),
    fox.WithClientIPStrategy(
	    // We are behind one or many trusted proxies that have all private-space IP addresses.
	    strategy.NewRightmostNonPrivate(fox.HeaderXForwardedFor),
    ),
)

f.MustHandle(http.MethodGet, "/foo/bar", func(c fox.Context) {
    ipAddr, err := c.ClientIP()
    if err != nil {
	    // If the current strategy is not able to derive the client IP, an error
	    // will be returned rather than falling back on an untrustworthy IP. It
	    // should be treated as an application issue or a misconfiguration.
	    panic(err)
    }
    fmt.Println(ipAddr.String())
})

Small optimisation have been achieved on the Context allocation.

goos: linux
goarch: amd64
pkg: github.com/tigerwill90/fox
cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
                    │   old.txt    │               new.txt               │
                    │    sec/op    │    sec/op     vs base               │
StaticAll-16          10.95µ ±  3%   11.04µ ±  1%       ~ (p=0.393 n=10)
GithubParamsAll-16    83.16n ±  3%   84.10n ±  1%       ~ (p=0.315 n=10)
OverlappingRoute-16   95.48n ±  0%   95.98n ±  1%  +0.52% (p=0.011 n=10)
StaticParallel-16     9.598n ±  5%   9.452n ±  7%       ~ (p=0.123 n=10)
CatchAll-16           31.62n ±  2%   31.11n ±  2%  -1.58% (p=0.012 n=10)
CatchAllParallel-16   5.502n ± 22%   5.236n ± 13%       ~ (p=0.912 n=10)
CloneWith-16          68.94n ±  5%   64.84n ±  1%  -5.93% (p=0.000 n=10)
geomean               71.97n         70.78n        -1.66%

@tigerwill90 tigerwill90 changed the title Feat/default logger middleware Default logger middleware Jun 23, 2024
@tigerwill90 tigerwill90 marked this pull request as ready for review June 25, 2024 19:45
Repository owner deleted a comment from codecov bot Jun 26, 2024
Copy link

codecov bot commented Jun 26, 2024

Codecov Report

Attention: Patch coverage is 86.60714% with 75 lines in your changes missing coverage. Please review.

Project coverage is 87.38%. Comparing base (2ba5953) to head (9876e11).
Report is 1 commits behind head on master.

Files Patch % Lines
internal/slogpretty/handler.go 70.92% 32 Missing and 9 partials ⚠️
logger.go 76.38% 14 Missing and 3 partials ⚠️
recovery.go 84.48% 6 Missing and 3 partials ⚠️
context.go 88.46% 3 Missing and 3 partials ⚠️
fox.go 84.61% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #33      +/-   ##
==========================================
- Coverage   88.08%   87.38%   -0.70%     
==========================================
  Files          12       15       +3     
  Lines        1678     1911     +233     
==========================================
+ Hits         1478     1670     +192     
- Misses        169      189      +20     
- Partials       31       52      +21     
Flag Coverage Δ
coverage.txt ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@tigerwill90 tigerwill90 requested a review from pawndev June 26, 2024 19:38
@tigerwill90 tigerwill90 merged commit 74b75c6 into master Jun 27, 2024
6 of 8 checks passed
@tigerwill90 tigerwill90 deleted the feat/default-logger-middleware branch June 27, 2024 15:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant