Compare commits

...

19 Commits

Author SHA1 Message Date
Renovate 6d5599e3f2 chore(deps): update golangci/golangci-lint docker tag to v1.58 (#26)
ci/woodpecker/push/test Pipeline was successful Details
Reviewed-on: #26
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2024-05-04 04:44:59 +00:00
Renovate c04f470209 chore(deps): update golangci/golangci-lint docker tag to v1.57 (#22)
ci/woodpecker/push/test Pipeline was successful Details
Reviewed-on: #22
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2024-03-30 04:43:45 +00:00
Renovate ec981ac676 chore(deps): update module github.com/stretchr/testify to v1.9.0 (#25)
ci/woodpecker/push/test Pipeline was successful Details
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [github.com/stretchr/testify](https://github.com/stretchr/testify) | require | minor | `v1.8.4` -> `v1.9.0` |

---

### Release Notes

<details>
<summary>stretchr/testify (github.com/stretchr/testify)</summary>

### [`v1.9.0`](https://github.com/stretchr/testify/releases/tag/v1.9.0)

[Compare Source](https://github.com/stretchr/testify/compare/v1.8.4...v1.9.0)

#### What's Changed

-   Fix Go modules version by [@&#8203;SuperQ](https://github.com/SuperQ) in https://github.com/stretchr/testify/pull/1394
-   Document that require is not safe to call in created goroutines by [@&#8203;programmer04](https://github.com/programmer04) in https://github.com/stretchr/testify/pull/1392
-   Remove myself from MAINTAINERS.md by [@&#8203;mvdkleijn](https://github.com/mvdkleijn) in https://github.com/stretchr/testify/pull/1367
-   Correct spelling/grammar by [@&#8203;echarrod](https://github.com/echarrod) in https://github.com/stretchr/testify/pull/1389
-   docs: Update URLs in README by [@&#8203;davidjb](https://github.com/davidjb) in https://github.com/stretchr/testify/pull/1349
-   Update mockery link to Github Pages in README by [@&#8203;LandonTClipp](https://github.com/LandonTClipp) in https://github.com/stretchr/testify/pull/1346
-   docs: Fix typos in tests and comments by [@&#8203;alexandear](https://github.com/alexandear) in https://github.com/stretchr/testify/pull/1410
-   CI: tests from go1.17 by [@&#8203;SuperQ](https://github.com/SuperQ) in https://github.com/stretchr/testify/pull/1409
-   Fix adding ? when no values passed by [@&#8203;lesichkovm](https://github.com/lesichkovm) in https://github.com/stretchr/testify/pull/1320
-   codegen: use standard header for generated files by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1406
-   mock: AssertExpectations log reason only on failure by [@&#8203;hikyaru-suzuki](https://github.com/hikyaru-suzuki) in https://github.com/stretchr/testify/pull/1360
-   assert: fix flaky TestNeverTrue by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1417
-   README: fix typos "set up" vs "setup" by [@&#8203;ossan-dev](https://github.com/ossan-dev) in https://github.com/stretchr/testify/pull/1428
-   mock: move regexp compilation outside of `Called` by [@&#8203;aud10slave](https://github.com/aud10slave) in https://github.com/stretchr/testify/pull/631
-   assert: refactor internal func getLen() by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1445
-   mock: deprecate type AnythingOfTypeArgument ([#&#8203;1434](https://github.com/stretchr/testify/issues/1434)) by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1441
-   Remove no longer needed assert.canConvert by [@&#8203;alexandear](https://github.com/alexandear) in https://github.com/stretchr/testify/pull/1470
-   assert: ObjectsAreEqual: use time.Equal for time.Time types by [@&#8203;tscales](https://github.com/tscales) in https://github.com/stretchr/testify/pull/1464
-   Bump actions/checkout from 3 to 4 by [@&#8203;dependabot](https://github.com/dependabot) in https://github.com/stretchr/testify/pull/1466
-   Bump actions/setup-go from 3.2.0 to 4.1.0 by [@&#8203;dependabot](https://github.com/dependabot) in https://github.com/stretchr/testify/pull/1451
-   fix: make EventuallyWithT concurrency safe by [@&#8203;czeslavo](https://github.com/czeslavo) in https://github.com/stretchr/testify/pull/1395
-   assert: fix httpCode and HTTPBody occur panic when http.Handler read Body by [@&#8203;hidu](https://github.com/hidu) in https://github.com/stretchr/testify/pull/1484
-   assert.EqualExportedValues: fix handling of arrays by [@&#8203;zrbecker](https://github.com/zrbecker) in https://github.com/stretchr/testify/pull/1473
-   .github: use latest Go versions by [@&#8203;kevinburkesegment](https://github.com/kevinburkesegment) in https://github.com/stretchr/testify/pull/1489
-   assert: Deprecate EqualExportedValues by [@&#8203;HaraldNordgren](https://github.com/HaraldNordgren) in https://github.com/stretchr/testify/pull/1488
-   suite: refactor test assertions by [@&#8203;alexandear](https://github.com/alexandear) in https://github.com/stretchr/testify/pull/1474
-   suite: fix SetupSubTest and TearDownSubTest execution order by [@&#8203;linusbarth](https://github.com/linusbarth) in https://github.com/stretchr/testify/pull/1471
-   docs: Fix deprecation comments for http package by [@&#8203;alexandear](https://github.com/alexandear) in https://github.com/stretchr/testify/pull/1335
-   Add map support doc comments to Subset and NotSubset by [@&#8203;jedevc](https://github.com/jedevc) in https://github.com/stretchr/testify/pull/1306
-   TestErrorIs/TestNotErrorIs: check error message contents by [@&#8203;craig65535](https://github.com/craig65535) in https://github.com/stretchr/testify/pull/1435
-   suite: fix subtest names (fix [#&#8203;1501](https://github.com/stretchr/testify/issues/1501)) by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1504
-   assert: improve unsafe.Pointer tests by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1505
-   assert: simplify isNil implementation by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1506
-   assert.InEpsilonSlice: fix expected/actual order and other improvements by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1483
-   Fix dependency cycle with objx [#&#8203;1292](https://github.com/stretchr/testify/issues/1292) by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1453
-   mock: refactor TestIsArgsEqual by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1444
-   mock: optimize argument matching checks by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1416
-   assert: fix TestEventuallyTimeout by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1412
-   CI: add go 1.21 in GitHub Actions by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1450
-   suite: fix recoverAndFailOnPanic to report test failure at the right location by [@&#8203;dolmen](https://github.com/dolmen) in https://github.com/stretchr/testify/pull/1502
-   Update maintainers by [@&#8203;brackendawson](https://github.com/brackendawson) in https://github.com/stretchr/testify/pull/1533
-   assert: Fix EqualValues to handle overflow/underflow by [@&#8203;arjunmahishi](https://github.com/arjunmahishi) in https://github.com/stretchr/testify/pull/1531
-   assert: better formatting for Len() error by [@&#8203;kevinburkesegment](https://github.com/kevinburkesegment) in https://github.com/stretchr/testify/pull/1485
-   Ensure AssertExpectations does not fail in skipped tests by [@&#8203;ianrose14](https://github.com/ianrose14) in https://github.com/stretchr/testify/pull/1331
-   suite: fix deadlock in suite.Require()/Assert() by [@&#8203;arjunmahishi](https://github.com/arjunmahishi) in https://github.com/stretchr/testify/pull/1535
-   Revert "assert: ObjectsAreEqual: use time.Equal for time.Time type" by [@&#8203;brackendawson](https://github.com/brackendawson) in https://github.com/stretchr/testify/pull/1537
-   \[chore] Add issue templates by [@&#8203;arjunmahishi](https://github.com/arjunmahishi) in https://github.com/stretchr/testify/pull/1538
-   Update the build status badge by [@&#8203;brackendawson](https://github.com/brackendawson) in https://github.com/stretchr/testify/pull/1540
-   Update Github workflows setup-go to V5 by [@&#8203;hendrywiranto](https://github.com/hendrywiranto) in https://github.com/stretchr/testify/pull/1545
-   Support Pointer to Struct in EqualExportedValues by [@&#8203;Lucaber](https://github.com/Lucaber) in https://github.com/stretchr/testify/pull/1517
-   README: drop link to gorc by [@&#8203;guettli](https://github.com/guettli) in https://github.com/stretchr/testify/pull/1248
-   http_assertions: honour the msgAndArgs provided with each assertion by [@&#8203;arjunmahishi](https://github.com/arjunmahishi) in https://github.com/stretchr/testify/pull/1548
-   fix typos in comments and tests by [@&#8203;ccoVeille](https://github.com/ccoVeille) in https://github.com/stretchr/testify/pull/1247
-   Include the auto-release notes in releases by [@&#8203;brackendawson](https://github.com/brackendawson) in https://github.com/stretchr/testify/pull/1550
-   Add `NotImplements` and variants by [@&#8203;hslatman](https://github.com/hslatman) in https://github.com/stretchr/testify/pull/1385
-   Add support to compare uintptr by [@&#8203;bogdandrutu](https://github.com/bogdandrutu) in https://github.com/stretchr/testify/pull/1339
-   build(deps): bump github.com/stretchr/objx from 0.5.1 to 0.5.2 by [@&#8203;dependabot](https://github.com/dependabot) in https://github.com/stretchr/testify/pull/1552

#### New Contributors

-   [@&#8203;SuperQ](https://github.com/SuperQ) made their first contribution in https://github.com/stretchr/testify/pull/1394
-   [@&#8203;programmer04](https://github.com/programmer04) made their first contribution in https://github.com/stretchr/testify/pull/1392
-   [@&#8203;echarrod](https://github.com/echarrod) made their first contribution in https://github.com/stretchr/testify/pull/1389
-   [@&#8203;davidjb](https://github.com/davidjb) made their first contribution in https://github.com/stretchr/testify/pull/1349
-   [@&#8203;LandonTClipp](https://github.com/LandonTClipp) made their first contribution in https://github.com/stretchr/testify/pull/1346
-   [@&#8203;alexandear](https://github.com/alexandear) made their first contribution in https://github.com/stretchr/testify/pull/1410
-   [@&#8203;lesichkovm](https://github.com/lesichkovm) made their first contribution in https://github.com/stretchr/testify/pull/1320
-   [@&#8203;dolmen](https://github.com/dolmen) made their first contribution in https://github.com/stretchr/testify/pull/1406
-   [@&#8203;hikyaru-suzuki](https://github.com/hikyaru-suzuki) made their first contribution in https://github.com/stretchr/testify/pull/1360
-   [@&#8203;ossan-dev](https://github.com/ossan-dev) made their first contribution in https://github.com/stretchr/testify/pull/1428
-   [@&#8203;aud10slave](https://github.com/aud10slave) made their first contribution in https://github.com/stretchr/testify/pull/631
-   [@&#8203;tscales](https://github.com/tscales) made their first contribution in https://github.com/stretchr/testify/pull/1464
-   [@&#8203;czeslavo](https://github.com/czeslavo) made their first contribution in https://github.com/stretchr/testify/pull/1395
-   [@&#8203;hidu](https://github.com/hidu) made their first contribution in https://github.com/stretchr/testify/pull/1484
-   [@&#8203;zrbecker](https://github.com/zrbecker) made their first contribution in https://github.com/stretchr/testify/pull/1473
-   [@&#8203;kevinburkesegment](https://github.com/kevinburkesegment) made their first contribution in https://github.com/stretchr/testify/pull/1489
-   [@&#8203;linusbarth](https://github.com/linusbarth) made their first contribution in https://github.com/stretchr/testify/pull/1471
-   [@&#8203;jedevc](https://github.com/jedevc) made their first contribution in https://github.com/stretchr/testify/pull/1306
-   [@&#8203;craig65535](https://github.com/craig65535) made their first contribution in https://github.com/stretchr/testify/pull/1435
-   [@&#8203;arjunmahishi](https://github.com/arjunmahishi) made their first contribution in https://github.com/stretchr/testify/pull/1531
-   [@&#8203;ianrose14](https://github.com/ianrose14) made their first contribution in https://github.com/stretchr/testify/pull/1331
-   [@&#8203;hendrywiranto](https://github.com/hendrywiranto) made their first contribution in https://github.com/stretchr/testify/pull/1545
-   [@&#8203;Lucaber](https://github.com/Lucaber) made their first contribution in https://github.com/stretchr/testify/pull/1517
-   [@&#8203;guettli](https://github.com/guettli) made their first contribution in https://github.com/stretchr/testify/pull/1248
-   [@&#8203;ccoVeille](https://github.com/ccoVeille) made their first contribution in https://github.com/stretchr/testify/pull/1247
-   [@&#8203;hslatman](https://github.com/hslatman) made their first contribution in https://github.com/stretchr/testify/pull/1385
-   [@&#8203;bogdandrutu](https://github.com/bogdandrutu) made their first contribution in https://github.com/stretchr/testify/pull/1339

**Full Changelog**: https://github.com/stretchr/testify/compare/v1.8.4...v1.9.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4xMzAuMCIsInVwZGF0ZWRJblZlciI6IjM3LjEzMC4wIiwidGFyZ2V0QnJhbmNoIjoibWFzdGVyIn0=-->

Reviewed-on: #25
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2024-03-02 05:39:03 +00:00
Renovate 2dcbf79078 chore(deps): update module go.uber.org/zap to v1.27.0 (#24)
ci/woodpecker/push/test Pipeline was successful Details
Reviewed-on: #24
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2024-02-22 04:40:21 +00:00
Renovate 2b863c0b43 chore(deps): update module github.com/go-chi/chi/v5 to v5.0.12 (#23)
ci/woodpecker/push/test Pipeline was successful Details
Reviewed-on: #23
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2024-02-18 05:32:36 +00:00
Renovate c2faabe3fd chore(deps): update module github.com/go-chi/chi/v5 to v5.0.11 (#20)
Reviewed-on: #20
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2023-12-21 04:14:16 +00:00
Renovate 908422fb76 chore(deps): update golangci/golangci-lint docker tag to v1.55 (#19)
ci/woodpecker/push/test Pipeline was successful Details
Reviewed-on: #19
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2023-10-22 05:41:16 +00:00
Renovate b446320fce chore(deps): update module go.uber.org/zap to v1.26.0 (#18)
ci/woodpecker/push/test Pipeline failed Details
Reviewed-on: #18
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2023-10-22 05:41:05 +00:00
Dawid Wysokiński 95cd0a13f3
chore: update README.md [CI SKIP] 2023-08-20 07:21:20 +02:00
Dawid Wysokiński bc41d0d7de
fix: incorrect image name
ci/woodpecker/push/test Pipeline was successful Details
2023-08-20 07:18:26 +02:00
Dawid Wysokiński 78893a70a2
feat: migrate from drone to woodpecker
ci/woodpecker/push/test Pipeline failed Details
2023-08-20 07:17:36 +02:00
Renovate 38e4720367 chore(deps): update module go.uber.org/zap to v1.25.0 (#16)
continuous-integration/drone/push Build is passing Details
Reviewed-on: #16
Co-authored-by: Renovate <renovate@dwysokinski.me>
Co-committed-by: Renovate <renovate@dwysokinski.me>
2023-08-10 03:35:13 +00:00
renovate 1a4780ee4d chore(deps): update module github.com/go-chi/chi/v5 to v5.0.10 (#15)
continuous-integration/drone/push Build is passing Details
Reviewed-on: #15
Co-authored-by: renovate <renovate@noreply.localhost>
Co-committed-by: renovate <renovate@noreply.localhost>
2023-07-14 03:23:04 +00:00
renovate ff3011b6eb chore(deps): update module github.com/stretchr/testify to v1.8.4 (#14)
continuous-integration/drone/push Build is passing Details
Reviewed-on: #14
Co-authored-by: renovate <renovate@noreply.localhost>
Co-committed-by: renovate <renovate@noreply.localhost>
2023-05-31 03:30:15 +00:00
renovate 3c7fb65673 chore(deps): update module github.com/stretchr/testify to v1.8.3 (#13)
continuous-integration/drone/push Build is passing Details
Reviewed-on: #13
Co-authored-by: renovate <renovate@noreply.localhost>
Co-committed-by: renovate <renovate@noreply.localhost>
2023-05-20 04:13:50 +00:00
Dawid Wysokiński 893b1cfd48
refactor: remove redundant http.CanonicalHeaderKey
continuous-integration/drone/push Build is passing Details
2023-05-12 08:10:55 +02:00
Dawid Wysokiński 0038d85083
feat: add option to log ip from other http.Request fields than just RemoteAddr
continuous-integration/drone/push Build is passing Details
2023-05-12 07:53:44 +02:00
renovate 1433429574 chore(deps): update module github.com/stretchr/testify to v1.8.2 (#12)
continuous-integration/drone/push Build is passing Details
Reviewed-on: #12
Co-authored-by: renovate <renovate@noreply.localhost>
Co-committed-by: renovate <renovate@noreply.localhost>
2023-05-09 09:17:08 +00:00
Dawid Wysokiński 63537e13dc
refactor: print ip without port
continuous-integration/drone/push Build is passing Details
2023-05-09 11:04:45 +02:00
9 changed files with 235 additions and 88 deletions

View File

@ -1,36 +0,0 @@
---
kind: pipeline
type: docker
name: test
steps:
- name: test
image: golang:1.20
commands:
- go test -race -coverprofile=coverage.txt -covermode=atomic ./...
trigger:
event:
- push
- pull_request
branch:
- master
---
kind: pipeline
type: docker
name: check-go-mod
steps:
- name: check go.mod
image: golang:1.20
commands:
- go mod tidy
- git diff --exit-code go.mod
trigger:
event:
- push
- pull_request
branch:
- master

124
.golangci.yml Normal file
View File

@ -0,0 +1,124 @@
run:
tests: true
timeout: 5m
linters:
disable-all: true
enable:
- asasalint
- asciicheck
- bodyclose
- bidichk
- exportloopref
- depguard
- errcheck
- gocritic
- gosec
- gofmt
- goimports
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- prealloc
- staticcheck
- typecheck
- unconvert
- unused
- lll
- nestif
- thelper
- nonamedreturns
- gocyclo
- gomnd
- tenv
- testpackage
- noctx
- tparallel
- usestdlibvars
- unconvert
- makezero
- grouper
- errname
- exhaustive
- tagliatelle
- contextcheck
- gocheckcompilerdirectives
- errname
- forcetypeassert
- durationcheck
- predeclared
- promlinter
- wastedassign
linters-settings:
lll:
line-length: 150
gocyclo:
min-complexity: 10
depguard:
rules:
main:
files:
- "$all"
deny:
- pkg: reflect
desc: Please don't use reflect package
- pkg: github.com/pkg/errors
desc: Should be replaced by standard lib errors package
govet:
enable:
- asmdecl
- assign
- atomic
- atomicalign
- bools
- buildtag
- cgocall
- composites
- copylocks
- deepequalerrors
- errorsas
- findcall
- framepointer
- httpresponse
- ifaceassert
- loopclosure
- lostcancel
- nilfunc
- nilness
- printf
- reflectvaluecompare
- shadow
- shift
- sigchanyzer
- sortslice
- stdmethods
- stringintconv
- structtag
- testinggoroutine
- tests
- unmarshal
- unreachable
- unsafeptr
- unusedresult
- unusedwrite
gomnd:
ignored-functions:
- strconv.FormatInt
- strconv.ParseInt
issues:
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- dupl
- gocyclo
- linters:
- lll
source: "^//go:generate "
- linters:
- lll
source: "^// @Param"

31
.woodpecker/test.yml Normal file
View File

@ -0,0 +1,31 @@
when:
- event: [pull_request]
- event: push
branch:
- ${CI_REPO_DEFAULT_BRANCH}
variables:
- &go_image 'golang:1.21'
steps:
test:
image: *go_image
group: test
pull: true
commands:
- go test -race -coverprofile=coverage.txt -covermode=atomic ./...
lint:
image: golangci/golangci-lint:v1.58
pull: true
group: test
commands:
- golangci-lint run
check-go-mod:
image: *go_image
group: test
pull: true
commands:
- go mod tidy
- git diff --exit-code go.mod

View File

@ -1,4 +1,4 @@
# chizap [![Build Status](https://drone.dwysokinski.me/api/badges/Kichiyaki/chizap/status.svg?ref=refs/heads/master)](https://drone.dwysokinski.me/Kichiyaki/chizap)
# chizap [![Build Status](https://woodpecker.dwysokinski.me/api/badges/4/status.svg)](https://woodpecker.dwysokinski.me/repos/4)
A request logging middleware for [go-chi](https://github.com/go-chi/chi) using [zap](https://github.com/uber-go/zap).

View File

@ -1,6 +1,7 @@
package chizap
import (
"net"
"net/http"
"go.uber.org/zap"
@ -12,13 +13,19 @@ type AdditionalFieldExtractor func(r *http.Request) []zap.Field
type config struct {
filters []Filter
ipFn func(r *http.Request) string
additionalFieldExtractors []AdditionalFieldExtractor
}
type Option func(*config)
func newConfig(opts ...Option) *config {
cfg := &config{}
cfg := &config{
ipFn: func(r *http.Request) string {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
},
}
for _, opt := range opts {
opt(cfg)
@ -38,9 +45,18 @@ func WithFilter(f Filter) Option {
}
// WithAdditionalFieldExtractor takes a function that will be called on every
// request and the returned fields will be added to a log entry.
// request and the returned fields will be added to the log entry.
func WithAdditionalFieldExtractor(extractor AdditionalFieldExtractor) Option {
return func(c *config) {
c.additionalFieldExtractors = append(c.additionalFieldExtractors, extractor)
}
}
// WithIPFn takes a function that will be called on every
// request and the returned ip will be added to the log entry.
// http.Request RemoteAddr is logged by default.
func WithIPFn(fn func(r *http.Request) string) Option {
return func(c *config) {
c.ipFn = fn
}
}

9
go.mod
View File

@ -3,15 +3,14 @@ module gitea.dwysokinski.me/Kichiyaki/chizap
go 1.18
require (
github.com/go-chi/chi/v5 v5.0.8
github.com/stretchr/testify v1.8.1
go.uber.org/zap v1.24.0
github.com/go-chi/chi/v5 v5.0.12
github.com/stretchr/testify v1.9.0
go.uber.org/zap v1.27.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.7.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

33
go.sum
View File

@ -1,32 +1,17 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0=
github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/go-chi/chi/v5 v5.0.12 h1:9euLV5sTrTNTRUU9POmDUvfxyj6LAABLUcEWO+JJb4s=
github.com/go-chi/chi/v5 v5.0.12/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec=
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -7,13 +7,10 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Logger returns a go-chi middleware that logs requests using go.uber.org/zap.
//
// Requests with status code >= 500 are logged using logger.Error.
// Requests with status code >= 400 are logged using logger.Warn.
// Other requests are logged using logger.Info.
func Logger(logger *zap.Logger, opts ...Option) func(next http.Handler) http.Handler {
cfg := newConfig(opts...)
return func(next http.Handler) http.Handler {
@ -38,7 +35,7 @@ func Logger(logger *zap.Logger, opts ...Option) func(next http.Handler) http.Han
fields := []zap.Field{
zap.Int("statusCode", statusCode),
zap.Duration("duration", end.Sub(start)),
zap.String("ip", r.RemoteAddr),
zap.String("ip", cfg.ipFn(r)),
zap.String("method", r.Method),
zap.String("query", query),
zap.String("path", path),
@ -49,17 +46,23 @@ func Logger(logger *zap.Logger, opts ...Option) func(next http.Handler) http.Han
zap.String("routePattern", chi.RouteContext(r.Context()).RoutePattern()),
}
for _, fn := range cfg.additionalFieldExtractors {
fields = append(fields, fn(r)...)
for _, f := range cfg.additionalFieldExtractors {
fields = append(fields, f(r)...)
}
if statusCode >= http.StatusInternalServerError {
logger.Error(path, fields...)
} else if statusCode >= http.StatusBadRequest {
logger.Warn(path, fields...)
} else {
logger.Info(path, fields...)
}
logger.Log(statusCodeToLogLvl(statusCode), path, fields...)
})
}
}
func statusCodeToLogLvl(statusCode int) zapcore.Level {
if statusCode >= http.StatusInternalServerError {
return zap.ErrorLevel
}
if statusCode >= http.StatusBadRequest {
return zap.WarnLevel
}
return zap.InfoLevel
}

View File

@ -1,11 +1,11 @@
package chizap_test
import (
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"gitea.dwysokinski.me/Kichiyaki/chizap"
"github.com/go-chi/chi/v5"
@ -23,30 +23,30 @@ func TestLogger(t *testing.T) {
name string
req *http.Request
excluded bool
expectedIP string
expectedLevel zapcore.Level
expectedRoutePattern string
expectedTimeFormat string
expectedAdditionalFields []zap.Field
}{
{
name: "/info?test=true",
req: httptest.NewRequest(http.MethodGet, "/info?test=true", nil),
expectedIP: "192.0.2.1",
expectedLevel: zap.InfoLevel,
expectedTimeFormat: time.RFC3339,
expectedRoutePattern: "/info",
},
{
name: "/warn?test=true",
req: httptest.NewRequest(http.MethodGet, "/warn?test=true", nil),
expectedIP: "192.0.2.1",
expectedLevel: zap.WarnLevel,
expectedTimeFormat: time.RFC3339,
expectedRoutePattern: "/warn",
},
{
name: "/error?test=true",
req: httptest.NewRequest(http.MethodGet, "/error?test=true", nil),
expectedIP: "192.0.2.1",
expectedLevel: zap.ErrorLevel,
expectedTimeFormat: time.RFC3339,
expectedRoutePattern: "/error",
},
{
@ -57,13 +57,24 @@ func TestLogger(t *testing.T) {
{
name: "/delete/123",
req: httptest.NewRequest(http.MethodDelete, "/delete/123", nil),
expectedIP: "192.0.2.1",
expectedLevel: zap.InfoLevel,
expectedTimeFormat: time.RFC3339,
expectedRoutePattern: "/delete/{id}",
expectedAdditionalFields: []zap.Field{
zap.String("id", "123"),
},
},
{
name: "/x-forwarded-for",
req: func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "/x-forwarded-for", nil)
req.Header.Set("X-Forwarded-For", "94.222.111.115")
return req
}(),
expectedIP: "94.222.111.115",
expectedLevel: zap.InfoLevel,
expectedRoutePattern: "/x-forwarded-for",
},
}
for _, tt := range tests {
@ -89,10 +100,14 @@ func TestLogger(t *testing.T) {
assert.Equal(t, tt.req.URL.Path, entry.Message)
assert.Equal(t, tt.expectedLevel, entry.Level)
require.Len(t, entry.Context, 11+len(tt.expectedAdditionalFields))
assert.Contains(t, entry.Context, zap.String("ip", tt.expectedIP))
assert.Contains(t, entry.Context, zap.Int("statusCode", rr.Code))
assert.Contains(t, entry.Context, zap.String("method", tt.req.Method))
assert.Contains(t, entry.Context, zap.String("path", tt.req.URL.Path))
assert.Contains(t, entry.Context, zap.String("query", tt.req.URL.RawQuery))
assert.Contains(t, entry.Context, zap.String("proto", tt.req.Proto))
assert.Contains(t, entry.Context, zap.String("referer", tt.req.Referer()))
assert.Contains(t, entry.Context, zap.String("userAgent", tt.req.UserAgent()))
assert.Contains(t, entry.Context, zap.String("routePattern", tt.expectedRoutePattern))
for _, f := range tt.expectedAdditionalFields {
assert.Contains(t, entry.Context, f)
@ -128,6 +143,13 @@ func newRouter(logger *zap.Logger) *chi.Mux {
zap.String("id", chi.URLParam(r, "id")),
}
}),
chizap.WithIPFn(func(r *http.Request) string {
if r.URL.Path != "/x-forwarded-for" {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}
return r.Header.Get("X-Forwarded-For")
}),
))
r.Get("/info", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
@ -141,6 +163,9 @@ func newRouter(logger *zap.Logger) *chi.Mux {
r.Get("/excluded", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Get("/x-forwarded-for", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Delete("/delete/{id}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})