Bump go-pkgz/rest to v1.24.0 and opt in to wildcard origins with credentials (#2157)

rest.CORS refuses "*" together with credentials since go-pkgz/rest#52, so the
bump and the option have to land together: the option does not exist in v1.22.0
and the panic fires at construction, inside routes(), which makes it a startup
failure rather than a request-time one.

The wildcard stays. The comment widget is embedded on arbitrary third-party
sites, so the set of origins is not knowable, which is why the escape hatch was
asked for upstream instead of accepting the panic. What it costs is unchanged
and now written next to the call: any site a signed-in user visits can read
authenticated responses, so state-changing requests have to keep being protected
by something other than the origin, X-XSRF-Token today.

The example module is tidied in the same commit, as it reaches go-pkgz/rest
through the replace directive and its indirect graph would otherwise keep the
old pin and fail the readonly module check in CI.

The bump also carries testify to v1.12.0, which drops go-spew and go-difflib
from the module graph.
This commit is contained in:
Dmitry Verkhoturov
2026-08-19 00:33:13 -05:00
committed by GitHub
parent 455d770899
commit 1f34984dab
43 changed files with 926 additions and 652 deletions
+2 -4
View File
@@ -6,7 +6,7 @@ require (
github.com/go-pkgz/jrpc v0.4.0
github.com/go-pkgz/lgr v0.12.3
github.com/jessevdk/go-flags v1.6.1
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.0
github.com/umputun/remark42/backend v1.1000.0
)
@@ -16,14 +16,12 @@ require (
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dlclark/regexp2/v2 v2.2.2 // indirect
github.com/go-pkgz/rest v1.22.0 // indirect
github.com/go-pkgz/rest v1.24.0 // indirect
github.com/go-pkgz/routegroup v1.6.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
+4 -8
View File
@@ -13,16 +13,14 @@ github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
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/dlclark/regexp2/v2 v2.2.2 h1:MYWvNYw8okuqNhwTYO587EZMiDruVa2vhV6fsGpfya0=
github.com/dlclark/regexp2/v2 v2.2.2/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
github.com/go-pkgz/jrpc v0.4.0 h1:oD7xiGrzDkndkuCjeHGugQXxbggLSV7O1QmHhoc5pYY=
github.com/go-pkgz/jrpc v0.4.0/go.mod h1:JFoY3bRjRyx4M3CbEVDFQStMB1m2gmQ7OjqFK7q3kOo=
github.com/go-pkgz/lgr v0.12.3 h1:QDug7kRkEsuQtruT9fNF5PVT2kZUqCDPc4GmsgS3fP8=
github.com/go-pkgz/lgr v0.12.3/go.mod h1:lpCDgVvCIxBHZp8+sGCj9MPctIzKZyZ3QdE19ddqd54=
github.com/go-pkgz/rest v1.22.0 h1:d3XFKlmAGBiU9MQER9/n46iXpyUr8IQUtfjU8JlqkkY=
github.com/go-pkgz/rest v1.22.0/go.mod h1:+AHzjHazq7Z3Tk/kRWOhbbAz/YZlUV40feC1Hf4NtbE=
github.com/go-pkgz/rest v1.24.0 h1:GAUCgx7U8xCOC2OynLjhCRMhtnMQH4d1mTdKpQyX2yI=
github.com/go-pkgz/rest v1.24.0/go.mod h1:dl3EWiuFB4hRTo2Sknj6UrQGFRAYvANK6/NyW8qQPxc=
github.com/go-pkgz/routegroup v1.6.0 h1:44XHZgF6JIIldRlv+zjg6SygULASmjifnfIQjwCT0e4=
github.com/go-pkgz/routegroup v1.6.0/go.mod h1:Pmu04fhgWhRtBMIJ8HXppnnzOPjnL/IEPBIdO2zmeqg=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
@@ -37,16 +35,14 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
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/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
+7
View File
@@ -123,6 +123,12 @@ func ParseTrustedProxies(entries []string) ([]*net.IPNet, error) {
// "*" and credentials enabled, rest.CORS reflects the request Origin into
// Access-Control-Allow-Origin (rather than a literal "*"), which browsers require
// for credentialed cross-origin requests.
//
// That combination is refused by default upstream, so it has to be asked for by name with
// CorsUnsafeAnyOriginWithCredentials. The wildcard stays because the comment widget is embedded on
// arbitrary third-party sites, which makes the set of origins unknowable. The consequence it carries
// is that any site a signed-in user visits can read authenticated responses, so state-changing
// requests have to keep being protected by something other than the origin, X-XSRF-Token today.
func corsMiddleware() func(http.Handler) http.Handler {
return R.CORS(
R.CorsAllowedOrigins("*"),
@@ -130,6 +136,7 @@ func corsMiddleware() func(http.Handler) http.Handler {
R.CorsAllowedHeaders("Accept", "Authorization", "Content-Type", "X-XSRF-Token", "X-JWT"),
R.CorsExposedHeaders("Authorization"),
R.CorsAllowCredentials(true),
R.CorsUnsafeAnyOriginWithCredentials(true),
R.CorsMaxAge(300),
)
}
+2 -4
View File
@@ -13,7 +13,7 @@ require (
github.com/go-pkgz/lgr v0.12.3
github.com/go-pkgz/notify v1.3.0
github.com/go-pkgz/repeater/v2 v2.2.0
github.com/go-pkgz/rest v1.22.0
github.com/go-pkgz/rest v1.24.0
github.com/go-pkgz/routegroup v1.6.0
github.com/go-pkgz/syncs v1.3.2
github.com/golang-jwt/jwt/v5 v5.3.1
@@ -25,7 +25,7 @@ require (
github.com/rs/xid v1.6.0
github.com/russross/blackfriday/v2 v2.1.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.0
go.etcd.io/bbolt v1.5.0
go.uber.org/goleak v1.3.0
golang.org/x/crypto v0.53.0
@@ -39,7 +39,6 @@ require (
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dghubble/oauth1 v0.7.3 // indirect
github.com/dlclark/regexp2/v2 v2.2.2 // indirect
github.com/go-oauth2/oauth2/v4 v4.5.4 // indirect
@@ -54,7 +53,6 @@ require (
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/klauspost/compress v1.18.7 // indirect
github.com/montanaflynn/stats v0.9.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/redis/go-redis/v9 v9.21.0 // indirect
github.com/rrivera/identicon v0.0.0-20240116195454-d5ba35832c0d // indirect
github.com/slack-go/slack v0.27.0 // indirect
+4 -6
View File
@@ -60,8 +60,8 @@ github.com/go-pkgz/repeater v1.2.0 h1:oJFvjyKdTDd5RCzpzxlzYIZFFj6Zfl17rE1aUfu6Uj
github.com/go-pkgz/repeater v1.2.0/go.mod h1:vypP6xamA53MFmafnGUucqOmALKk36xgKu2hSG73LHM=
github.com/go-pkgz/repeater/v2 v2.2.0 h1:8nZR/NaknmLfx2YMHbr78u9OL4Xj+8+romm9dz4FpMg=
github.com/go-pkgz/repeater/v2 v2.2.0/go.mod h1:RgX5vUbLKq7PV82QUDP5pFbQS1os4Z+U9XzKymK23A8=
github.com/go-pkgz/rest v1.22.0 h1:d3XFKlmAGBiU9MQER9/n46iXpyUr8IQUtfjU8JlqkkY=
github.com/go-pkgz/rest v1.22.0/go.mod h1:+AHzjHazq7Z3Tk/kRWOhbbAz/YZlUV40feC1Hf4NtbE=
github.com/go-pkgz/rest v1.24.0 h1:GAUCgx7U8xCOC2OynLjhCRMhtnMQH4d1mTdKpQyX2yI=
github.com/go-pkgz/rest v1.24.0/go.mod h1:dl3EWiuFB4hRTo2Sknj6UrQGFRAYvANK6/NyW8qQPxc=
github.com/go-pkgz/routegroup v1.6.0 h1:44XHZgF6JIIldRlv+zjg6SygULASmjifnfIQjwCT0e4=
github.com/go-pkgz/routegroup v1.6.0/go.mod h1:Pmu04fhgWhRtBMIJ8HXppnnzOPjnL/IEPBIdO2zmeqg=
github.com/go-pkgz/syncs v1.3.2 h1:gmioASlJNy3gNosPlgvWOM2QP0Hdjzn2u+/sUShgd8E=
@@ -117,8 +117,6 @@ github.com/montanaflynn/stats v0.9.0 h1:tsBJ0RXwph9BmAuFoCmqGv6e8xa0MENQ8m0ptKq2
github.com/montanaflynn/stats v0.9.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/moul/http2curl v1.0.0 h1:dRMWoAtb+ePxMlLkrCbAqh4TlPHXvoGUSQ323/9Zahs=
github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ=
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/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
@@ -139,8 +137,8 @@ github.com/smartystreets/assertions v1.1.0 h1:MkTeG1DMwsrdH7QtLXy5W+fUxWq+vmb6cL
github.com/smartystreets/assertions v1.1.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
github.com/tidwall/btree v1.8.1 h1:27ehoXvm5AG/g+1VxLS1SD3vRhp/H7LuEfwNvddEdmA=
github.com/tidwall/btree v1.8.1/go.mod h1:jBbTdUWhSZClZWoDg54VnvV7/54modSOzDN7VXftj1A=
github.com/tidwall/buntdb v1.3.2 h1:qd+IpdEGs0pZci37G4jF51+fSKlkuUTMXuHhXL1AkKg=
+84 -7
View File
@@ -92,6 +92,8 @@ Logs request, request handling time and response. Log record fields in order of
_remote IP can be masked with user defined function_
_request body can be transformed before logging with a user-defined function (`BodyFn`), e.g. to mask credentials. It only runs when body logging is on (`WithBody`), and receives the body along with a `truncated` flag that is set when the body exceeded `MaxBodySize` - the function can use it to emit a marker instead of logging a partial body it can't safely process_
example: `019/03/05 17:26:12.976 [INFO] GET - /api/v1/find?site=remark - 8e228e9cfece - 200 (115) - 4.47784618s`
### Recoverer middleware
@@ -100,10 +102,15 @@ Recoverer is a middleware that recovers from panics, logs the panic (and a backt
and returns an HTTP 500 (Internal Server Error) status if possible.
It prevents server crashes in case of panic in one of the controllers.
`http.ErrAbortHandler` is re-panicked untouched and neither logged nor turned into a 500, as `net/http`
relies on the sentinel reaching the server to abort the response and close the connection.
### OnlyFrom middleware
OnlyFrom middleware allows access from a limited list of source IPs.
Such IPs can be defined as complete ip (like 192.168.1.12), prefix (129.168.) or CIDR (192.168.0.0/16).
Complete IP rules use semantic address equality (so equivalent IPv6 spellings match), CIDRs use network containment,
and all other rules use literal textual prefix matching.
The middleware will respond with `StatusForbidden` (403) if the request comes from a different IP.
It supports both IPv4 and IPv6 and checks the usual headers like `X-Forwarded-For` and `X-Real-IP` and the remote address.
@@ -111,12 +118,20 @@ _Note: headers should be trusted and set by a proxy, otherwise it is possible to
### Metrics middleware
Metrics middleware responds to GET /metrics with list of [expvar](https://golang.org/pkg/expvar/).
Optionally allows a restricted list of source ips.
Metrics middleware responds to GET /metrics with list of [expvar](https://golang.org/pkg/expvar/),
limited to a list of source ips, i.e. `rest.Metrics("127.0.0.1", "192.168.0.0/16")`.
Called without any ip, as `rest.Metrics()`, it rejects every request.
To serve the endpoint to everyone, ask for it explicitly with `rest.MetricsAllowAll()`. Note that expvar
publishes `cmdline`, which usually carries the flag values the process was started with, so only do this
where something else already keeps the endpoint private.
### BlackWords middleware
BlackWords middleware doesn't allow user-defined words in the request body.
It reads the whole body to inspect it and responds with `StatusBadRequest` (400) if the body can't be read.
The body is not capped on its own, so put `SizeLimit` in front of it to bound what a request can allocate:
`rest.Wrap(handler, rest.SizeLimit(1024*1024), rest.BlackWords("word1", "word2"))`.
### SizeLimit middleware
@@ -163,13 +178,51 @@ router.Use(rest.StripSlashes)
Sets a number of HTTP headers to prevent a router (handler's) response from being cached by an upstream proxy and/or client.
### CacheControl middleware
Sets `Cache-Control` with the given expiration and an `Etag` derived from the request URL plus a version,
either a fixed string (`CacheControl`) or one computed per request (`CacheControlDynamic`).
```go
router.Use(rest.CacheControl(time.Hour, "v1"))
router.Use(rest.CacheControlDynamic(time.Hour, func(r *http.Request) string { return userVersion(r) }))
```
Conditional requests are handled for GET and HEAD only: an `If-None-Match` carrying the current etag gets a
`StatusNotModified` (304) and the handler is skipped. The header is parsed as a proper tag list, so
comma-separated values and the `W/` weak-validator prefix are understood and a tag only matches in full;
repeated `If-None-Match` fields count as one list, so a match in any of them is honoured.
Requests with other methods are passed to the handler untouched, since their preconditions need to know
whether the resource exists and this middleware can't answer that. The `*` wildcard is not matched for the
same reason, and a request also carrying `If-Match` or `If-Unmodified-Since` is left to the handler, since
those outrank `If-None-Match` and may call for a `StatusPreconditionFailed` (412) that a 304 would hide.
### Headers middleware
Sets headers (passed as key:value) to requests. I.e. `rest.Headers("Server:MyServer", "X-Blah:Foo")`
### Gzip middleware
Compresses response with gzip.
Compresses response with gzip. Adds `Vary: Accept-Encoding` to every response it handles, compressed or not,
so shared caches key on the encoding rather than serving gzip bytes to a client that never asked for them.
The decision is made on the **response** content type, either the one the handler set or, when it set none,
the type sniffed from the first chunk of the body. By default the common textual types are compressed
(`text/html`, `text/plain`, `text/css`, `text/xml`, `text/javascript`, `application/javascript`,
`application/x-javascript`, `application/json`); pass your own list to override, i.e. `rest.Gzip("text/html")`.
`Accept-Encoding` is parsed rather than substring-matched, so `gzip;q=0` is honoured as a refusal and a named
`gzip` entry outranks a `*` wildcard. Compression is skipped for responses that carry no body (204 and 304),
for responses the handler already encoded (`Content-Encoding` set), and for partial responses (206 or a
`Content-Range`), whose offsets describe the uncompressed representation. `Content-Length` is dropped when the
body is compressed, interim 1xx responses pass through without becoming the final status, and `Flush` and
`Hijack` pass through so streaming responses and protocol upgrades keep working. The wrapper offers those two
only when the writer beneath it does, so composing with `Timeout`, which offers neither, does not leave a
handler with a `Flush` that silently does nothing.
One deviation is worth knowing about: sniffing means the status cannot be sent until the body arrives, so when
a handler calls `WriteHeader` without setting `Content-Type`, headers it changes before the first `Write` still
reach the client, where `net/http` would have ignored them.
### RealIP middleware
@@ -219,18 +272,43 @@ router.Use(rest.CORS(
Features:
- Automatic preflight (OPTIONS) handling
- Origin validation with case-insensitive matching
- Credentials support (reflects origin instead of `*`)
- Credentials support (reflects the request origin instead of `*`)
- Configurable cache duration for preflight results
- Cache-correct `Vary` headers (adds `Access-Control-Request-Method` and `Access-Control-Request-Headers` on preflight)
Available options:
- `CorsAllowedOrigins(origins...)` - allowed origins (default: `*`)
- `CorsAllowedOrigins(origins...)` - allowed origins (default: `*`), can't include `*` with credentials enabled
- `CorsAllowedMethods(methods...)` - allowed HTTP methods (default: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD)
- `CorsAllowedHeaders(headers...)` - allowed request headers (default: Accept, Content-Type, Authorization, X-Requested-With)
- `CorsExposedHeaders(headers...)` - headers exposed to client
- `CorsAllowCredentials(bool)` - enable credentials (cookies, auth headers)
- `CorsUnsafeAnyOriginWithCredentials(bool)` - allow `*` together with credentials, see below
- `CorsMaxAge(seconds)` - preflight cache duration
`CORS` panics if credentials are enabled while `*` is among the allowed origins, the default list included.
That combination reflects any origin back together with `Access-Control-Allow-Credentials: true`, which lets
any site a signed-in user visits read authenticated responses, so it should not be reached by accident.
Name the origins instead:
```go
router.Use(rest.CORS(
rest.CorsAllowedOrigins("https://app.example.com"),
rest.CorsAllowCredentials(true),
))
```
A service that genuinely has to accept credentialed requests from arbitrary third-party origins, such as an
embeddable widget, can opt back in explicitly. Do this only when state-changing requests are protected by
something other than the origin:
```go
router.Use(rest.CORS(
rest.CorsAllowedOrigins("*"),
rest.CorsAllowCredentials(true),
rest.CorsUnsafeAnyOriginWithCredentials(true),
))
```
### Secure middleware
Adds security headers to responses. By default sets: `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`, `X-XSS-Protection`, and `Strict-Transport-Security` (for HTTPS only).
@@ -434,7 +512,7 @@ example with chi router:
- `realip.Get` - returns client's IP address
- `rest.ParseFromTo` - parses "from" and "to" request's query params with various formats
- `rest.DecodeJSON` - decodes request body to the provided struct
- `rest.EncodeJSON` - encodes response body from the provided struct, sets `Content-Type` to `application/json` and sends the status code
- `rest.EncodeJSON` - encodes response body from the provided struct, sets `Content-Type` to `application/json` and sends the status code. The value is encoded before anything is written, so an encoding failure leaves the response uncommitted and the caller can still replace it with an error status. Write failures are reported too, by which point the response has already been committed
## Profiler
@@ -451,4 +529,3 @@ Profiler is a convenient sub-router used for mounting net/http/pprof, i.e.
```
It exposes a bunch of `/pprof/*` endpoints as well as `/vars`. Builtin support for `onlyIps` allows restricting access, which is important if it runs on a publicly exposed port. However, counting on IP check only is not that reliable way to limit request and for production use it would be better to add some sort of auth (for example provided `BasicAuth` middleware) or run with a separate http server, exposed to internal ip/port only.
+3 -1
View File
@@ -68,7 +68,9 @@ func (b *Benchmarks) Handler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
st := b.nowFn()
defer func() {
b.update(time.Since(st))
// both ends come from nowFn so the measurement follows the same clock as the bucketing,
// which lets tests drive it instead of waiting on wall time
b.update(b.nowFn().Sub(st))
}()
next.ServeHTTP(w, r)
}
+13 -9
View File
@@ -13,16 +13,20 @@ func BlackWords(words ...string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if content, err := io.ReadAll(r.Body); err == nil {
body := strings.ToLower(string(content))
r.Body = io.NopCloser(bytes.NewReader(content))
content, err := io.ReadAll(r.Body)
if err != nil {
// the body can't be inspected, refuse rather than pass a partially consumed one through
_ = EncodeJSON(w, http.StatusBadRequest, JSON{"error": "can't read request body"})
return
}
r.Body = io.NopCloser(bytes.NewReader(content))
if body != "" {
for _, word := range words {
if strings.Contains(body, strings.ToLower(word)) {
_ = EncodeJSON(w, http.StatusForbidden, JSON{"error": "one of blacklisted words detected"})
return
}
body := strings.ToLower(string(content))
if body != "" {
for _, word := range words {
if strings.Contains(body, strings.ToLower(word)) {
_ = EncodeJSON(w, http.StatusForbidden, JSON{"error": "one of blacklisted words detected"})
return
}
}
}
+35 -25
View File
@@ -10,31 +10,13 @@ import (
// CacheControl is a middleware setting cache expiration. Using url+version for etag
func CacheControl(expiration time.Duration, version string) func(http.Handler) http.Handler {
etag := func(r *http.Request, version string) string {
s := fmt.Sprintf("%s:%s", version, r.URL.String())
return fmt.Sprintf("%x", sha1.Sum([]byte(s))) //nolint
}
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
e := `"` + etag(r, version) + `"`
w.Header().Set("Etag", e)
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, no-cache", int(expiration.Seconds())))
if match := r.Header.Get("If-None-Match"); match != "" {
if strings.Contains(match, e) {
w.WriteHeader(http.StatusNotModified)
return
}
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return CacheControlDynamic(expiration, func(*http.Request) string { return version })
}
// CacheControlDynamic is a middleware setting cache expiration. Using url+ func(r) for etag
// CacheControlDynamic is a middleware setting cache expiration. Using url+ func(r) for etag.
// Conditional requests are handled for GET and HEAD only, answering 304 when If-None-Match carries
// the current etag. Other methods are passed to the handler, as this middleware doesn't know enough
// about the resource to enforce their preconditions.
func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Request) string) func(http.Handler) http.Handler {
etag := func(r *http.Request, version string) string {
@@ -49,8 +31,15 @@ func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Reques
w.Header().Set("Etag", e)
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, no-cache", int(expiration.Seconds())))
if match := r.Header.Get("If-None-Match"); match != "" {
if strings.Contains(match, e) {
// If-Match and If-Unmodified-Since outrank If-None-Match and can call for a 412, which only
// the handler can decide, so answering 304 over them would hide it. Presence is enough,
// and it is checked across every field as repeated ones all count
preconditioned := len(r.Header.Values("If-Match")) > 0 || len(r.Header.Values("If-Unmodified-Since")) > 0
safeMethod := r.Method == http.MethodGet || r.Method == http.MethodHead
if safeMethod && !preconditioned {
if etagMatches(r.Header.Values("If-None-Match"), e) {
w.WriteHeader(http.StatusNotModified)
return
}
@@ -60,3 +49,24 @@ func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Reques
return http.HandlerFunc(fn)
}
}
// etagMatches reports whether any If-None-Match header field carries the given etag.
// Repeated fields form a single list, so all of them are examined. Handles comma-separated lists
// and the W/ weak-validator prefix, comparing with the weak comparison of RFC 9110. The "*"
// wildcard is deliberately not matched here, as it asks whether any representation exists and the
// middleware can't answer that before the handler runs.
func etagMatches(headers []string, etag string) bool {
etag = strings.TrimPrefix(strings.TrimSpace(etag), "W/")
for _, header := range headers {
for tag := range strings.SplitSeq(header, ",") {
tag = strings.TrimSpace(tag)
if tag == "" || tag == "*" {
continue
}
if strings.TrimPrefix(tag, "W/") == etag {
return true
}
}
}
return false
}
+30 -4
View File
@@ -2,6 +2,7 @@ package rest
import (
"net/http"
"slices"
"strconv"
"strings"
)
@@ -10,7 +11,7 @@ import (
// Use CorsOpt functions to customize.
type CORSConfig struct {
// AllowedOrigins is a list of origins that may access the resource.
// use "*" to allow all origins (not recommended with credentials).
// use "*" to allow all origins, rejected by CORS when combined with credentials.
// default: ["*"]
AllowedOrigins []string
// AllowedMethods is a list of methods the client is allowed to use.
@@ -23,9 +24,14 @@ type CORSConfig struct {
// default: empty
ExposedHeaders []string
// AllowCredentials indicates whether the request can include credentials.
// when true, AllowedOrigins cannot be "*" (browser security restriction).
// when true, AllowedOrigins cannot contain "*" unless UnsafeAnyOriginWithCredentials is set,
// and CORS panics otherwise.
// default: false
AllowCredentials bool
// UnsafeAnyOriginWithCredentials permits "*" together with credentials, making the middleware
// reflect whatever Origin the request carries alongside Access-Control-Allow-Credentials.
// default: false
UnsafeAnyOriginWithCredentials bool
// MaxAge indicates how long (in seconds) the results of a preflight can be cached.
// default: 0 (no caching)
MaxAge int
@@ -47,7 +53,7 @@ func defaultCORSConfig() CORSConfig {
}
// CorsAllowedOrigins sets the list of allowed origins.
// Use "*" to allow all origins (not recommended with credentials).
// Use "*" to allow all origins, which CORS rejects when credentials are enabled.
func CorsAllowedOrigins(origins ...string) CorsOpt {
return func(c *CORSConfig) {
c.AllowedOrigins = origins
@@ -76,13 +82,24 @@ func CorsExposedHeaders(headers ...string) CorsOpt {
}
// CorsAllowCredentials enables or disables credentials.
// When true, AllowedOrigins cannot be "*".
// When true, AllowedOrigins cannot contain "*" and CORS panics if it does.
func CorsAllowCredentials(allow bool) CorsOpt {
return func(c *CORSConfig) {
c.AllowCredentials = allow
}
}
// CorsUnsafeAnyOriginWithCredentials permits "*" among the allowed origins together with credentials.
// The middleware then reflects whatever Origin the request carries and sends
// Access-Control-Allow-Credentials: true with it, so any site a signed-in user visits can read
// authenticated responses. Only use it for a service meant to be embedded on arbitrary third-party
// origins, and make sure state-changing requests are protected by something other than the origin.
func CorsUnsafeAnyOriginWithCredentials(allow bool) CorsOpt {
return func(c *CORSConfig) {
c.UnsafeAnyOriginWithCredentials = allow
}
}
// CorsMaxAge sets how long (in seconds) preflight results can be cached.
func CorsMaxAge(seconds int) CorsOpt {
return func(c *CORSConfig) {
@@ -93,12 +110,21 @@ func CorsMaxAge(seconds int) CorsOpt {
// CORS is middleware that handles Cross-Origin Resource Sharing.
// It handles preflight OPTIONS requests and sets appropriate headers.
// By default allows all origins with common methods and headers.
//
// Panics if credentials are enabled while "*" is among the allowed origins, including the default
// origin list. Such a configuration reflects any origin back with Access-Control-Allow-Credentials,
// which lets any site read authenticated responses. Enumerate the origins instead.
func CORS(opts ...CorsOpt) func(http.Handler) http.Handler {
cfg := defaultCORSConfig()
for _, opt := range opts {
opt(&cfg)
}
if cfg.AllowCredentials && !cfg.UnsafeAnyOriginWithCredentials && slices.Contains(cfg.AllowedOrigins, "*") {
panic(`rest: CORS with credentials can't allow "*" as an origin, list the allowed origins explicitly ` +
`or opt in with CorsUnsafeAnyOriginWithCredentials`)
}
// pre-compute joined strings for performance
methodsStr := strings.Join(cfg.AllowedMethods, ", ")
headersStr := strings.Join(cfg.AllowedHeaders, ", ")
+9 -5
View File
@@ -116,7 +116,9 @@ type customFS struct {
listing bool
}
// Open file on FS, for directory enforce index.html and fail on a missing index
// Open file on FS, for directory enforce index.html and fail on a missing index.
// Every handle opened here is either returned to the caller or closed, as http.FileServer
// closes only the file it gets back.
func (cfs customFS) Open(name string) (http.File, error) {
f, err := cfs.fs.Open(name)
@@ -129,19 +131,21 @@ func (cfs customFS) Open(name string) (http.File, error) {
finfo, err := f.Stat()
if err != nil {
_ = f.Close()
return nil, err
}
if finfo.IsDir() {
index := strings.TrimSuffix(name, "/") + "/index.html"
if _, err := cfs.fs.Open(index); err == nil { // index.html will be served if found
indexFile, ierr := cfs.fs.Open(index)
if ierr == nil { // index.html will be served if found
_ = indexFile.Close() // opened to probe for existence only, http.FileServer opens it again on its own
return f, nil
}
// no index.html in directory
if !cfs.listing { // listing disabled
if _, err := cfs.fs.Open(index); err != nil {
return nil, err
}
_ = f.Close()
return nil, ierr
}
}
+253 -37
View File
@@ -1,9 +1,13 @@
package rest
import (
"bufio"
"compress/gzip"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
)
@@ -23,21 +27,220 @@ var gzPool = sync.Pool{
New: func() any { return gzip.NewWriter(io.Discard) },
}
// gzipResponseWriter defers the compression decision until the response content type is known,
// either from the header the handler set or sniffed from the first chunk of the body.
//
// One consequence is worth knowing about: when the handler calls WriteHeader without a Content-Type,
// the status cannot be sent yet, because the body has to be sniffed first. Headers changed between
// that call and the first Write therefore still reach the client, where net/http would have ignored
// them. Handlers that mutate headers after WriteHeader are relying on a no-op, so this is more
// permissive rather than wrong, but it is a difference from the bare ResponseWriter.
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
gzCts []string
gz *gzip.Writer
status int
statusSet bool
decided bool
wroteHeader bool
hijacked bool
}
func (w *gzipResponseWriter) WriteHeader(status int) {
w.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(status)
// 1xx are interim responses, they pass straight through and the final status still follows.
// 101 is the exception, it hands the connection to another protocol and is final.
if status >= 100 && status < 200 && status != http.StatusSwitchingProtocols {
w.ResponseWriter.WriteHeader(status)
return
}
if w.statusSet {
return // net/http keeps the first final status, so later calls are ignored here too
}
w.statusSet = true
w.status = status
// with a content type in hand the decision can be made right away, otherwise it waits for the
// first Write so the body can be sniffed. 101 cannot wait: the upgrade sequence carries no body
// and usually no content type, and the Hijack that follows would leave the status unsent
if ctype := w.Header().Get("Content-Type"); ctype != "" || status == http.StatusSwitchingProtocols {
w.decide(ctype)
w.commit()
}
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
if !w.decided {
ctype := w.Header().Get("Content-Type")
// net/http suppresses sniffing for an already encoded body, guessing a type from
// compressed bytes would only mislabel it
if ctype == "" && w.Header().Get("Content-Encoding") == "" {
ctype = http.DetectContentType(b)
w.Header().Set("Content-Type", ctype)
}
w.decide(ctype)
}
if !w.wroteHeader {
w.commit()
}
if w.gz != nil {
return w.gz.Write(b)
}
return w.ResponseWriter.Write(b)
}
// Gzip is a middleware compressing response
// decide turns compression on if the response content type is one of the configured types
func (w *gzipResponseWriter) decide(ctype string) {
w.decided = true
switch w.status {
case http.StatusSwitchingProtocols, http.StatusNoContent, http.StatusResetContent, http.StatusNotModified:
return // these carry no body to compress
}
if w.Header().Get("Content-Encoding") != "" {
return // the handler encoded the body itself, wrapping it again would mislabel the result
}
if w.status == http.StatusPartialContent || w.Header().Get("Content-Range") != "" {
return // the range metadata describes the identity representation
}
for _, c := range w.gzCts {
if !strings.HasPrefix(strings.ToLower(ctype), strings.ToLower(c)) {
continue
}
gz := gzPool.Get().(*gzip.Writer)
gz.Reset(w.ResponseWriter)
w.gz = gz
w.Header().Set("Content-Encoding", "gzip")
w.Header().Del("Content-Length") // the handler's length describes the uncompressed body
return
}
}
func (w *gzipResponseWriter) commit() {
w.wroteHeader = true
if w.status == 0 {
w.status = http.StatusOK
}
w.ResponseWriter.WriteHeader(w.status)
}
// close finishes the gzip stream and makes sure the status reaches the client even if the handler
// wrote no body at all. finished reports whether the handler returned normally: when it panicked
// instead, an uncommitted response is left alone so a recoverer upstream can still make it a 500.
func (w *gzipResponseWriter) close(finished bool) {
if w.hijacked {
return // the handler owns the connection now, nothing may be written to it
}
if w.wroteHeader || finished {
if !w.decided {
w.decide(w.Header().Get("Content-Type"))
}
if !w.wroteHeader {
w.commit()
}
}
if w.gz == nil {
return
}
_ = w.gz.Close()
gzPool.Put(w.gz)
w.gz = nil
}
// flush pushes buffered data out, keeping streaming responses working through the compressor
func (w *gzipResponseWriter) flush() {
if w.hijacked {
return
}
// decide before the headers leave, otherwise a later write could be compressed after the client
// was already told the body is identity
if !w.decided {
w.decide(w.Header().Get("Content-Type"))
}
if !w.wroteHeader {
w.commit()
}
if w.gz != nil {
_ = w.gz.Flush()
}
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// hijack passes through to the underlying writer for protocol upgrades
func (w *gzipResponseWriter) hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("http.Hijacker not supported")
}
// finish the stream first, whatever the handler already wrote has to reach the wire before the
// connection changes hands, and a failure there means truncated output rather than something to
// swallow behind a successful hijack
if w.gz != nil {
if err := w.gz.Close(); err != nil {
return nil, nil, fmt.Errorf("finish gzip stream before hijack: %w", err)
}
}
conn, rw, err := h.Hijack()
if err != nil {
// the connection was not taken over, so the writer stays attached and closed: a handler that
// carries on writing now gets an error instead of appending raw bytes to a body already
// advertised as gzip, and the deferred close still returns the writer to the pool
return nil, nil, err
}
if w.gz != nil {
gzPool.Put(w.gz)
w.gz = nil
}
w.hijacked = true
return conn, rw, nil
}
// the wrapper must offer exactly the optional interfaces the underlying writer has, otherwise a
// handler's type assertion succeeds and the call then does nothing, which is how http.TimeoutHandler
// (offering neither) would silently lose a Flush
type gzipFlusher struct{ *gzipResponseWriter }
func (w gzipFlusher) Flush() { w.flush() }
type gzipHijacker struct{ *gzipResponseWriter }
func (w gzipHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.hijack() }
type gzipFlushHijacker struct{ *gzipResponseWriter }
func (w gzipFlushHijacker) Flush() { w.flush() }
func (w gzipFlushHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.hijack() }
// wrapGzipWriter picks the variant matching the capabilities of the writer underneath
func wrapGzipWriter(gw *gzipResponseWriter) http.ResponseWriter {
_, isFlusher := gw.ResponseWriter.(http.Flusher)
_, isHijacker := gw.ResponseWriter.(http.Hijacker)
switch {
case isFlusher && isHijacker:
return gzipFlushHijacker{gw}
case isFlusher:
return gzipFlusher{gw}
case isHijacker:
return gzipHijacker{gw}
}
return gw
}
// Unwrap exposes the underlying writer to http.ResponseController
func (w *gzipResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
// Gzip is a middleware compressing response. The decision is made on the response content type,
// so it applies to what the handler actually produced. Content types default to the common textual
// ones and can be overridden by the caller.
func Gzip(contentTypes ...string) func(http.Handler) http.Handler {
gzCts := gzDefaultContentTypes
@@ -45,44 +248,57 @@ func Gzip(contentTypes ...string) func(http.Handler) http.Handler {
gzCts = contentTypes
}
contentType := func(r *http.Request) string {
result := r.Header.Get("Content-type")
if result == "" {
return "application/octet-stream"
}
return result
}
f := func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
// the representation depends on Accept-Encoding, caches must key on it even when not compressing
w.Header().Add("Vary", "Accept-Encoding")
if !acceptsGzip(r.Header.Values("Accept-Encoding")) {
next.ServeHTTP(w, r)
return
}
var gzOk bool
ctype := contentType(r)
for _, c := range gzCts {
if strings.HasPrefix(strings.ToLower(ctype), strings.ToLower(c)) {
gzOk = true
break
}
}
gw := &gzipResponseWriter{ResponseWriter: w, gzCts: gzCts}
finished := false
defer func() { gw.close(finished) }()
if !gzOk {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(w)
defer gz.Close()
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
next.ServeHTTP(wrapGzipWriter(gw), r)
finished = true
})
}
return f
}
// acceptsGzip reports whether the client accepts gzip, honoring an explicit q=0 rejection.
// A named gzip entry decides the answer on its own, as it takes precedence over the "*" wildcard.
// Repeated Accept-Encoding fields form a single list, so every field is examined.
func acceptsGzip(headers []string) bool {
var wildcard, wildcardSeen bool
for _, header := range headers {
for enc := range strings.SplitSeq(header, ",") {
name, params, _ := strings.Cut(strings.TrimSpace(enc), ";")
n := strings.ToLower(strings.TrimSpace(name))
if n != "gzip" && n != "*" {
continue
}
acceptable := !rejectedByQuality(params)
if n == "gzip" {
return acceptable
}
if !wildcardSeen {
wildcard, wildcardSeen = acceptable, true
}
}
}
return wildcard
}
// rejectedByQuality reports whether the parameters of an Accept-Encoding entry carry q=0
func rejectedByQuality(params string) bool {
q, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(params)), "q=")
if !ok {
return false
}
v, err := strconv.ParseFloat(strings.TrimSpace(q), 64)
return err == nil && v == 0
}
+35 -7
View File
@@ -26,6 +26,7 @@ type Middleware struct {
ipFn func(ip string) string
userFn func(r *http.Request) (string, error)
subjFn func(r *http.Request) (string, error)
bodyFn func(body string, truncated bool) string
log Backend
apacheCombined bool
}
@@ -104,6 +105,9 @@ func (l *Middleware) Handler(next http.Handler) http.Handler {
if unescURL, err := url.QueryUnescape(rawurl); err == nil {
rawurl = unescURL
}
// unescaping can surface line breaks the encoded url hid, collapse them the same way
// the body is collapsed so an embedded break can't forge additional log records
rawurl = lineBreaks.Replace(rawurl)
remoteIP, err := realip.Get(r)
if err != nil {
@@ -131,7 +135,7 @@ func (l *Middleware) Handler(next http.Handler) http.Handler {
body: body,
}
l.log.Logf(formater(r, p))
l.log.Logf("%s", formater(r, p))
}()
next.ServeHTTP(ww, r)
@@ -191,7 +195,7 @@ func (l *Middleware) formatApacheCombined(r *http.Request, p *logParts) string {
bld.WriteString(p.method)
bld.WriteString(" ")
bld.WriteString(p.rawURL)
bld.WriteString(`" `)
bld.WriteString(" ")
bld.WriteString(r.Proto)
bld.WriteString(`" `)
bld.WriteString(strconv.Itoa(p.statusCode))
@@ -208,6 +212,19 @@ func (l *Middleware) formatApacheCombined(r *http.Request, p *logParts) string {
var reMultWhtsp = regexp.MustCompile(`[\s\p{Zs}]{2,}`)
// lineBreaks maps every character that can start a new line to a space, so a body
// can't forge extra log records. reMultWhtsp only collapses runs of two or more, so
// a lone CR or a Unicode line separator would otherwise slip through.
var lineBreaks = strings.NewReplacer(
"\n", " ", // LF
"\r", " ", // CR
"\v", " ", // vertical tab
"\f", " ", // form feed
"\u0085", " ", // NEL
"\u2028", " ", // line separator
"\u2029", " ", // paragraph separator
)
func (l *Middleware) getBody(r *http.Request) string {
if !l.logBody {
return ""
@@ -226,13 +243,24 @@ func (l *Middleware) getBody(r *http.Request) string {
// https://golang.org/pkg/net/http/#Handler
r.Body = io.NopCloser(reader)
if body != "" {
body = strings.ReplaceAll(body, "\n", " ")
body = reMultWhtsp.ReplaceAllString(body, " ")
// the transform owns the logged body: it receives the body (capped at
// maxBodySize) and a flag telling it whether more was dropped, and decides
// how to render it - mask values, summarize, or emit a marker for a
// truncated body. an empty body has nothing to transform, so it is left
// alone. without a transform the body is logged as read, with the "..."
// marker appended when it was truncated.
switch {
case l.bodyFn != nil && body != "":
body = l.bodyFn(body, hasMore)
case hasMore:
body += "..."
}
if hasMore {
body += "..."
// always collapse to a single line, regardless of the transform, so an
// embedded line break in the body can't forge additional log lines.
if body != "" {
body = lineBreaks.Replace(body)
body = reMultWhtsp.ReplaceAllString(body, " ")
}
return body
+14
View File
@@ -49,6 +49,20 @@ func SubjFn(subjFn func(r *http.Request) (string, error)) Option {
}
}
// BodyFn sets a transform applied to the request body before it is logged, e.g. to
// mask secrets. It only runs when body logging is enabled (see WithBody) and the
// body is non-empty; if bodyFn is nil the body is logged unchanged. bodyFn receives
// the body (capped at MaxBodySize) and a truncated flag that is true when the body was longer than
// MaxBodySize and got cut short - a masker can use it to emit a marker instead of
// risking a pass-through of a partial body it cannot parse. The returned string is
// what gets logged, so bodyFn owns the content; the logger still collapses it to a
// single line to keep one log record per request.
func BodyFn(bodyFn func(body string, truncated bool) string) Option {
return func(l *Middleware) {
l.bodyFn = bodyFn
}
}
// ApacheCombined sets format to Apache Combined Log.
// See http://httpd.apache.org/docs/2.2/logs.html#combined
func ApacheCombined(l *Middleware) {
+19 -4
View File
@@ -7,14 +7,29 @@ import (
"strings"
)
// Metrics responds to GET /metrics with list of expvar
// Metrics responds to GET /metrics with list of expvar, limited to the given source ips.
// Called without any ip it rejects every request, as an endpoint nobody can reach is the safe
// default for one that publishes expvar; use MetricsAllowAll to serve it to everyone on purpose.
func Metrics(onlyIps ...string) func(http.Handler) http.Handler {
return metricsHandler(false, onlyIps)
}
// MetricsAllowAll responds to GET /metrics with list of expvar for any source, without any ip check.
// expvar exposes cmdline, which usually carries the flag values the process was started with, so
// only use this where something else already keeps the endpoint private.
func MetricsAllowAll() func(http.Handler) http.Handler {
return metricsHandler(true, nil)
}
func metricsHandler(allowAll bool, onlyIps []string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && strings.HasSuffix(strings.ToLower(r.URL.Path), "/metrics") {
if matched, ip, err := matchSourceIP(r, onlyIps); !matched || err != nil {
_ = EncodeJSON(w, http.StatusForbidden, JSON{"error": fmt.Sprintf("ip %s rejected", ip)})
return
if !allowAll {
if matched, ip, err := matchSourceIP(r, onlyIps); !matched || err != nil {
_ = EncodeJSON(w, http.StatusForbidden, JSON{"error": fmt.Sprintf("ip %s rejected", ip)})
return
}
}
expvar.Handler().ServeHTTP(w, r)
return
+6 -3
View File
@@ -96,15 +96,18 @@ func Health(path string, checkers ...func(ctx context.Context) (name string, err
}
// Recoverer is a middleware that recovers from panics, logs the panic and returns a HTTP 500 status if possible.
// http.ErrAbortHandler is passed through untouched, as net/http relies on it reaching the server to abort
// the response and close the connection.
func Recoverer(l logger.Backend) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
l.Logf("request panic for %s from %s, %v", r.URL.String(), r.RemoteAddr, rvr)
if rvr != http.ErrAbortHandler {
l.Logf(string(debug.Stack()))
if rvr == http.ErrAbortHandler {
panic(rvr)
}
l.Logf("request panic for %s from %s, %v", r.URL.String(), r.RemoteAddr, rvr)
l.Logf(string(debug.Stack()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
+12 -3
View File
@@ -10,7 +10,8 @@ import (
)
// OnlyFrom middleware allows access for limited list of source IPs.
// Such IPs can be defined as complete ip (like 192.168.1.12), prefix (129.168.) or CIDR (192.168.0.0/16)
// Rules can be complete IPs (like 192.168.1.12), textual prefixes (129.168.), or CIDRs (192.168.0.0/16).
// Complete IPs use semantic address equality, CIDRs use network containment, and all other rules use prefix matching.
func OnlyFrom(onlyIps ...string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
@@ -42,12 +43,20 @@ func matchSourceIP(r *http.Request, ips []string) (result bool, match string, er
if err != nil {
return false, "", fmt.Errorf("can't get realip: %w", err) // we can't get ip, so no match
}
// check for ip prefix or CIDR
parsedIP := net.ParseIP(ip)
// check for cidr, complete ip, or ip prefix
for _, exclIP := range ips {
if _, cidrnet, err := net.ParseCIDR(exclIP); err == nil {
if cidrnet.Contains(net.ParseIP(ip)) {
if cidrnet.Contains(parsedIP) {
return true, ip, nil
}
continue
}
if allowedIP := net.ParseIP(exclIP); allowedIP != nil {
if allowedIP.Equal(parsedIP) {
return true, ip, nil
}
continue
}
if strings.HasPrefix(ip, exclIP) {
return true, ip, nil
+10 -3
View File
@@ -105,12 +105,19 @@ func DecodeJSON[T any](r *http.Request, res *T) error {
return nil
}
// EncodeJSON encodes given type to http.ResponseWriter and sets status code and content type header
// EncodeJSON encodes given type to http.ResponseWriter and sets status code and content type header.
// The value is encoded before anything is written, so an encoding failure leaves the response
// uncommitted and the caller is free to replace it with an error status. Write failures are reported
// as well, by which point the response has already been committed.
func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error {
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(v); err != nil {
return fmt.Errorf("encode json: %w", err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return fmt.Errorf("encode json: %w", err)
if _, err := w.Write(buf.Bytes()); err != nil {
return fmt.Errorf("write json: %w", err)
}
return nil
}
+20 -8
View File
@@ -84,7 +84,7 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -124,7 +124,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri
return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// assert.Errorf(t, err, "error message %s", "formatted")
@@ -144,8 +144,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
@@ -190,10 +190,10 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") {
// assert.EventuallyWithTf(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -552,7 +552,7 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool
return NoDirExists(t, path, append([]interface{}{msg}, args...)...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if assert.NoErrorf(t, err, "error message %s", "formatted") {
@@ -849,7 +849,19 @@ func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time,
return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// assert.YAMLEqf(t, expected, actual, "error message %s", "formatted")
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
+38 -14
View File
@@ -146,7 +146,7 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs
return Equal(a.t, expected, actual, msgAndArgs...)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -158,7 +158,7 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...
return EqualError(a.t, theError, errString, msgAndArgs...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -240,7 +240,7 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string
return Equalf(a.t, expected, actual, msg, args...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Error(err)
@@ -269,8 +269,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ..
return ErrorAsf(a.t, err, target, msg, args...)
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContains(err, expectedErrorSubString)
@@ -281,8 +281,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs .
return ErrorContains(a.t, theError, contains, msgAndArgs...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted")
@@ -311,7 +311,7 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter
return ErrorIsf(a.t, err, target, msg, args...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Errorf(err, "error message %s", "formatted")
@@ -372,10 +372,10 @@ func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// a.EventuallyWithTf(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1096,7 +1096,7 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{})
return NoDirExistsf(a.t, path, msg, args...)
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoError(err) {
@@ -1109,7 +1109,7 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
return NoError(a.t, err, msgAndArgs...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoErrorf(err, "error message %s", "formatted") {
@@ -1690,7 +1690,19 @@ func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Ti
return WithinRangef(a.t, actual, start, end, msg, args...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEq(expected, actual)
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1698,7 +1710,19 @@ func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interf
return YAMLEq(a.t, expected, actual, msgAndArgs...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEqf(expected, actual, "error message %s", "formatted")
func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
+13 -1
View File
@@ -9,7 +9,7 @@ import (
func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool {
objKind := reflect.TypeOf(object).Kind()
if objKind != reflect.Slice && objKind != reflect.Array {
return false
return Fail(t, fmt.Sprintf("object %T is not an ordered collection", object), msgAndArgs...)
}
objValue := reflect.ValueOf(object)
@@ -50,6 +50,9 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareR
// assert.IsIncreasing(t, []float{1, 2})
// assert.IsIncreasing(t, []string{"a", "b"})
func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
}
@@ -59,6 +62,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonIncreasing(t, []float{2, 1})
// assert.IsNonIncreasing(t, []string{"b", "a"})
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
}
@@ -68,6 +74,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
// assert.IsDecreasing(t, []float{2, 1})
// assert.IsDecreasing(t, []string{"b", "a"})
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
}
@@ -77,5 +86,8 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonDecreasing(t, []float{1, 2})
// assert.IsNonDecreasing(t, []string{"a", "b"})
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return isOrdered(t, object, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
}
+82 -63
View File
@@ -17,11 +17,10 @@ import (
"unicode"
"unicode/utf8"
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
// Wrapper around gopkg.in/yaml.v3
"github.com/stretchr/testify/assert/yaml"
"github.com/stretchr/testify/internal/difflib"
"github.com/stretchr/testify/internal/spew"
)
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
@@ -33,19 +32,19 @@ type TestingT interface {
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
// for table driven tests.
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
type ComparisonAssertionFunc = func(TestingT, interface{}, interface{}, ...interface{}) bool
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
// for table driven tests.
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
type ValueAssertionFunc = func(TestingT, interface{}, ...interface{}) bool
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
// for table driven tests.
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
type BoolAssertionFunc = func(TestingT, bool, ...interface{}) bool
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
type ErrorAssertionFunc = func(TestingT, error, ...interface{}) bool
// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful
// for table driven tests.
@@ -325,13 +324,15 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
func indentMessageLines(message string, longestLabelLen int) string {
outBuf := new(bytes.Buffer)
for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
// no need to align first line because it starts at the correct location (after the label)
if i != 0 {
// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
scanner := bufio.NewScanner(strings.NewReader(message))
for firstLine := true; scanner.Scan(); firstLine = false {
if !firstLine {
fmt.Fprint(outBuf, "\n\t"+strings.Repeat(" ", longestLabelLen+1)+"\t")
}
outBuf.WriteString(scanner.Text())
fmt.Fprint(outBuf, scanner.Text())
}
if err := scanner.Err(); err != nil {
return fmt.Sprintf("cannot display message: %s", err)
}
return outBuf.String()
@@ -544,9 +545,8 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b
if !same {
// both are pointers but not the same type & pointing to the same address
return Fail(t, fmt.Sprintf("Not same: \n"+
"expected: %p %#[1]v\n"+
"actual : %p %#[2]v",
expected, actual), msgAndArgs...)
"expected: %[2]s (%[1]T)(%[1]p)\n"+
"actual : %[4]s (%[3]T)(%[3]p)", expected, truncatingFormat("%#v", expected), actual, truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -571,8 +571,8 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
if same {
return Fail(t, fmt.Sprintf(
"Expected and actual point to the same object: %p %#[1]v",
expected), msgAndArgs...)
"Expected and actual point to the same object: %p %s",
expected, truncatingFormat("%#v", expected)), msgAndArgs...)
}
return true
}
@@ -604,25 +604,26 @@ func samePointers(first, second interface{}) (same bool, ok bool) {
// to a type conversion in the Go grammar.
func formatUnequalValues(expected, actual interface{}) (e string, a string) {
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
return fmt.Sprintf("%T(%s)", expected, truncatingFormat("%#v", expected)),
fmt.Sprintf("%T(%s)", actual, truncatingFormat("%#v", actual))
}
switch expected.(type) {
case time.Duration:
return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
}
return truncatingFormat(expected), truncatingFormat(actual)
return truncatingFormat("%#v", expected), truncatingFormat("%#v", actual)
}
// truncatingFormat formats the data and truncates it if it's too long.
//
// This helps keep formatted error messages lines from exceeding the
// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
func truncatingFormat(data interface{}) string {
value := fmt.Sprintf("%#v", data)
max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
if len(value) > max {
value = value[0:max] + "<... truncated>"
func truncatingFormat(format string, data interface{}) string {
value := fmt.Sprintf(format, data)
// Give us space for two truncated objects and the surrounding sentence.
maxMessageSize := bufio.MaxScanTokenSize/2 - 100
if len(value) > maxMessageSize {
value = value[0:maxMessageSize] + "<... truncated>"
}
return value
}
@@ -743,7 +744,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
return Fail(t, fmt.Sprintf("Expected nil, but got: %s", truncatingFormat("%#v", object)), msgAndArgs...)
}
// isEmpty gets whether the specified object is considered empty or not.
@@ -793,7 +794,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
Fail(t, fmt.Sprintf("Should be empty, but was %s", truncatingFormat("%v", object)), msgAndArgs...)
}
return pass
@@ -836,11 +837,11 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
}
l, ok := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", truncatingFormat("%v", object)), msgAndArgs...)
}
if l != length {
return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
return Fail(t, fmt.Sprintf("%q should have %d item(s), but has %d", truncatingFormat("%v", object), length, l), msgAndArgs...)
}
return true
}
@@ -889,7 +890,7 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{
}
if ObjectsAreEqual(expected, actual) {
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -904,7 +905,7 @@ func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...inte
}
if ObjectsAreEqualValues(expected, actual) {
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
}
return true
@@ -964,10 +965,10 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo
ok, found := containsElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
}
return true
@@ -986,10 +987,10 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{})
ok, found := containsElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
}
if found {
return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s should not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
}
return true
@@ -1031,10 +1032,10 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
av := actualMap.MapIndex(k)
if !av.IsValid() {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
}
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
}
}
@@ -1056,7 +1057,7 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", list), element), msgAndArgs...)
}
}
@@ -1082,12 +1083,12 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
listKind := reflect.TypeOf(list).Kind()
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", list, listKind), msgAndArgs...)
}
subsetKind := reflect.TypeOf(subset).Kind()
if subsetKind != reflect.Array && subsetKind != reflect.Slice && subsetKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", subset, subsetKind), msgAndArgs...)
}
if subsetKind == reflect.Map && listKind == reflect.Map {
@@ -1106,7 +1107,7 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
}
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
}
subsetList := reflect.ValueOf(subset)
@@ -1121,14 +1122,14 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
element := subsetList.Index(i).Interface()
ok, found := containsElement(list, element)
if !ok {
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
}
if !found {
return true
}
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
}
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
@@ -1343,9 +1344,15 @@ func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs .
if !funcDidPanic {
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
}
panicErr, ok := panicValue.(error)
if !ok || panicErr.Error() != errString {
return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
panicErr, isError := panicValue.(error)
if !isError || panicErr.Error() != errString {
msg := fmt.Sprintf("func %#v should panic with error message:\t%#v\n", f, errString)
if isError {
msg += fmt.Sprintf("\tError message:\t%#v\n", panicErr.Error())
}
msg += fmt.Sprintf("\tPanic value:\t%#v\n", panicValue)
msg += fmt.Sprintf("\tPanic stack:\t%s\n", panickedStack)
return Fail(t, msg, msgAndArgs...)
}
return true
@@ -1624,7 +1631,7 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m
Errors
*/
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if assert.NoError(t, err) {
@@ -1635,13 +1642,13 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
return Fail(t, fmt.Sprintf("Received unexpected error:\n%s", truncatingFormat("%+v", err)), msgAndArgs...)
}
return true
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// assert.Error(t, err)
@@ -1656,7 +1663,7 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
return true
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -1674,13 +1681,13 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
if expected != actual {
return Fail(t, fmt.Sprintf("Error message not equal:\n"+
"expected: %q\n"+
"actual : %q", expected, actual), msgAndArgs...)
"actual : %s", expected, truncatingFormat("%q", actual)), msgAndArgs...)
}
return true
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// assert.ErrorContains(t, err, expectedErrorSubString)
@@ -1694,7 +1701,7 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
actual := theError.Error()
if !strings.Contains(actual, contains) {
return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
return Fail(t, fmt.Sprintf("Error %s does not contain %#v", truncatingFormat("%#v", actual), contains), msgAndArgs...)
}
return true
@@ -1760,7 +1767,7 @@ func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
h.Helper()
}
if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
return Fail(t, fmt.Sprintf("Should be zero, but was %s", truncatingFormat("%v", i)), msgAndArgs...)
}
return true
}
@@ -1874,7 +1881,19 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// assert.YAMLEq(t, expected, actual)
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2188,8 +2207,8 @@ func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
chain := buildErrorChainString(err, false)
return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
"expected: %q\n"+
"in chain: %s", expectedText, chain,
"expected: %s\n"+
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2211,8 +2230,8 @@ func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
chain := buildErrorChainString(err, false)
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
"found: %q\n"+
"in chain: %s", expectedText, chain,
"found: %s\n"+
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2236,7 +2255,7 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{
return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
"expected: %s\n"+
"in chain: %s", expectedType, chain,
"in chain: %s", expectedType, truncatingFormat("%s", chain),
), msgAndArgs...)
}
@@ -2254,7 +2273,7 @@ func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interfa
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
"found: %s\n"+
"in chain: %s", reflect.TypeOf(target).Elem().String(), chain,
"in chain: %s", reflect.TypeOf(target).Elem().String(), truncatingFormat("%s", chain),
), msgAndArgs...)
}
+2 -2
View File
@@ -40,8 +40,8 @@
//
// # Assertions
//
// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
// All assertion functions take, as the first argument, the `*testing.T` object provided by the
// Assertions allow you to easily write test code, and are global funcs in the assert package.
// All assertion functions take, as the first argument, the [*testing.T] object provided by the
// testing framework. This allows the assertion funcs to write the failings and other details to
// the correct place.
//
@@ -24,4 +24,4 @@ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -8,11 +8,14 @@
//
// - unified_diff
//
// - context_diff
//
// Getting unified diffs was the main goal of the port. Keep in mind this code
// is mostly suitable to output text differences in a human friendly way, there
// are no guarantees generated diffs are consumable by patch(1).
//
// This package was adopted from [github.com/pmezard/go-difflib] which
// is no longer maintained.
//
// [github.com/pmezard/go-difflib]: https://github.com/pmezard/go-difflib
package difflib
import (
@@ -37,13 +40,6 @@ func max(a, b int) int {
return b
}
func calculateRatio(matches, length int) float64 {
if length > 0 {
return 2.0 * float64(matches) / float64(length)
}
return 1.0
}
type Match struct {
A int
B int
@@ -103,14 +99,6 @@ func NewMatcher(a, b []string) *SequenceMatcher {
return &m
}
func NewMatcherWithJunk(a, b []string, autoJunk bool,
isJunk func(string) bool) *SequenceMatcher {
m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
m.SetSeqs(a, b)
return &m
}
// Set two sequences to be compared.
func (m *SequenceMatcher) SetSeqs(a, b []string) {
m.SetSeq1(a)
@@ -199,12 +187,15 @@ func (m *SequenceMatcher) isBJunk(s string) bool {
// If IsJunk is not defined:
//
// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// and for all (i',j',k') meeting those conditions,
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// In other words, of all maximal matching blocks, return one that
// starts earliest in a, and of all those maximal matching blocks that
@@ -451,66 +442,6 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
return groups
}
// Return a measure of the sequences' similarity (float in [0,1]).
//
// Where T is the total number of elements in both sequences, and
// M is the number of matches, this is 2.0*M / T.
// Note that this is 1 if the sequences are identical, and 0 if
// they have nothing in common.
//
// .Ratio() is expensive to compute if you haven't already computed
// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
// want to try .QuickRatio() or .RealQuickRation() first to get an
// upper bound.
func (m *SequenceMatcher) Ratio() float64 {
matches := 0
for _, m := range m.GetMatchingBlocks() {
matches += m.Size
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// Return an upper bound on ratio() relatively quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute.
func (m *SequenceMatcher) QuickRatio() float64 {
// viewing a and b as multisets, set matches to the cardinality
// of their intersection; this counts the number of matches
// without regard to order, so is clearly an upper bound
if m.fullBCount == nil {
m.fullBCount = map[string]int{}
for _, s := range m.b {
m.fullBCount[s] = m.fullBCount[s] + 1
}
}
// avail[x] is the number of times x appears in 'b' less the
// number of times we've seen it in 'a' so far ... kinda
avail := map[string]int{}
matches := 0
for _, s := range m.a {
n, ok := avail[s]
if !ok {
n = m.fullBCount[s]
}
avail[s] = n - 1
if n > 0 {
matches += 1
}
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// Return an upper bound on ratio() very quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute than either .Ratio() or .QuickRatio().
func (m *SequenceMatcher) RealQuickRatio() float64 {
la, lb := len(m.a), len(m.b)
return calculateRatio(min(la, lb), la+lb)
}
// Convert range to the "ed" format
func formatRangeUnified(start, stop int) string {
// Per the diff spec at http://www.unix.org/single_unix_specification/
@@ -652,117 +583,6 @@ func formatRangeContext(start, stop int) string {
return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
}
type ContextDiff UnifiedDiff
// Compare two sequences of lines; generate the delta as a context diff.
//
// Context diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by diff.Context
// which defaults to three.
//
// By default, the diff control lines (those with *** or ---) are
// created with a trailing newline.
//
// For inputs that do not have trailing newlines, set the diff.Eol
// argument to "" so that the output will be uniformly newline free.
//
// The context diff format normally has a header for filenames and
// modification times. Any or all of these may be specified using
// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
// The modification times are normally expressed in the ISO 8601 format.
// If not specified, the strings default to blanks.
func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
buf := bufio.NewWriter(writer)
defer buf.Flush()
var diffErr error
wf := func(format string, args ...interface{}) {
_, err := buf.WriteString(fmt.Sprintf(format, args...))
if diffErr == nil && err != nil {
diffErr = err
}
}
ws := func(s string) {
_, err := buf.WriteString(s)
if diffErr == nil && err != nil {
diffErr = err
}
}
if len(diff.Eol) == 0 {
diff.Eol = "\n"
}
prefix := map[byte]string{
'i': "+ ",
'd': "- ",
'r': "! ",
'e': " ",
}
started := false
m := NewMatcher(diff.A, diff.B)
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
}
}
first, last := g[0], g[len(g)-1]
ws("***************" + diff.Eol)
range1 := formatRangeContext(first.I1, last.I2)
wf("*** %s ****%s", range1, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'd' {
for _, cc := range g {
if cc.Tag == 'i' {
continue
}
for _, line := range diff.A[cc.I1:cc.I2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
range2 := formatRangeContext(first.J1, last.J2)
wf("--- %s ----%s", range2, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'i' {
for _, cc := range g {
if cc.Tag == 'd' {
continue
}
for _, line := range diff.B[cc.J1:cc.J2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
}
return diffErr
}
// Like WriteContextDiff but returns the diff a string.
func GetContextDiffString(diff ContextDiff) (string, error) {
w := &bytes.Buffer{}
err := WriteContextDiff(w, diff)
return string(w.Bytes()), err
}
// Split a string on "\n" while preserving them. The output can be used
// as input for UnifiedDiff and ContextDiff structures.
func SplitLines(s string) []string {
+12
View File
@@ -0,0 +1,12 @@
go-spew
=======
[![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org)
Go-spew implements a deep pretty printer for Go data structures to aid in
debugging. A comprehensive suite of tests with 100% test coverage is provided
to ensure proper functionality.
## License
Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
@@ -18,6 +18,7 @@
// tag is deprecated and thus should not be used.
// Go versions prior to 1.4 are disabled because they use a different layout
// for interfaces which make the implementation of unsafeReflectValue more complex.
//go:build !js && !appengine && !safe && !disableunsafe && go1.4
// +build !js,!appengine,!safe,!disableunsafe,go1.4
package spew
@@ -16,6 +16,7 @@
// when the code is running on Google App Engine, compiled by GopherJS, or
// "-tags safe" is added to the go build command line. The "disableunsafe"
// tag is deprecated and thus should not be used.
//go:build js || appengine || safe || disableunsafe || !go1.4
// +build js appengine safe disableunsafe !go1.4
package spew
@@ -254,15 +254,15 @@ pointer addresses used to indirect to the final value. It provides the
following features over the built-in printing facilities provided by the fmt
package:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
The configuration options are controlled by modifying the public members
of c. See ConfigState for options documentation.
@@ -295,12 +295,12 @@ func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{})
// NewDefaultConfig returns a ConfigState with the following default settings.
//
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
// Indent: " "
// MaxDepth: 0
// DisableMethods: false
// DisablePointerMethods: false
// ContinueOnMethod: false
// SortKeys: false
func NewDefaultConfig() *ConfigState {
return &ConfigState{Indent: " "}
}
@@ -21,35 +21,36 @@ debugging.
A quick overview of the additional features spew provides over the built-in
printing facilities for Go data types are as follows:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output (only when using
Dump style)
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output (only when using
Dump style)
There are two different approaches spew allows for dumping Go data structures:
* Dump style which prints with newlines, customizable indentation,
and additional debug information such as types and all pointer addresses
used to indirect to the final value
* A custom Formatter interface that integrates cleanly with the standard fmt
package and replaces %v, %+v, %#v, and %#+v to provide inline printing
similar to the default %v while providing the additional functionality
outlined above and passing unsupported format verbs such as %x and %q
along to fmt
- Dump style which prints with newlines, customizable indentation,
and additional debug information such as types and all pointer addresses
used to indirect to the final value
- A custom Formatter interface that integrates cleanly with the standard fmt
package and replaces %v, %+v, %#v, and %#+v to provide inline printing
similar to the default %v while providing the additional functionality
outlined above and passing unsupported format verbs such as %x and %q
along to fmt
Quick Start
# Quick Start
This section demonstrates how to quickly get started with spew. See the
sections below for further details on formatting and configuration options.
To dump a variable with full newlines, indentation, type, and pointer
information use Dump, Fdump, or Sdump:
spew.Dump(myVar1, myVar2, ...)
spew.Fdump(someWriter, myVar1, myVar2, ...)
str := spew.Sdump(myVar1, myVar2, ...)
@@ -58,12 +59,13 @@ Alternatively, if you would prefer to use format strings with a compacted inline
printing style, use the convenience wrappers Printf, Fprintf, etc with
%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
%#+v (adds types and pointer addresses):
spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
Configuration Options
# Configuration Options
Configuration of spew is handled by fields in the ConfigState type. For
convenience, all of the top-level functions use a global state available
@@ -74,51 +76,52 @@ equivalent to the top-level functions. This allows concurrent configuration
options. See the ConfigState documentation for more details.
The following configuration options are available:
* Indent
String to use for each indentation level for Dump functions.
It is a single space by default. A popular alternative is "\t".
* MaxDepth
Maximum number of levels to descend into nested data structures.
There is no limit by default.
- Indent
String to use for each indentation level for Dump functions.
It is a single space by default. A popular alternative is "\t".
* DisableMethods
Disables invocation of error and Stringer interface methods.
Method invocation is enabled by default.
- MaxDepth
Maximum number of levels to descend into nested data structures.
There is no limit by default.
* DisablePointerMethods
Disables invocation of error and Stringer interface methods on types
which only accept pointer receivers from non-pointer variables.
Pointer method invocation is enabled by default.
- DisableMethods
Disables invocation of error and Stringer interface methods.
Method invocation is enabled by default.
* DisablePointerAddresses
DisablePointerAddresses specifies whether to disable the printing of
pointer addresses. This is useful when diffing data structures in tests.
- DisablePointerMethods
Disables invocation of error and Stringer interface methods on types
which only accept pointer receivers from non-pointer variables.
Pointer method invocation is enabled by default.
* DisableCapacities
DisableCapacities specifies whether to disable the printing of
capacities for arrays, slices, maps and channels. This is useful when
diffing data structures in tests.
- DisablePointerAddresses
DisablePointerAddresses specifies whether to disable the printing of
pointer addresses. This is useful when diffing data structures in tests.
* ContinueOnMethod
Enables recursion into types after invoking error and Stringer interface
methods. Recursion after method invocation is disabled by default.
- DisableCapacities
DisableCapacities specifies whether to disable the printing of
capacities for arrays, slices, maps and channels. This is useful when
diffing data structures in tests.
* SortKeys
Specifies map keys should be sorted before being printed. Use
this to have a more deterministic, diffable output. Note that
only native types (bool, int, uint, floats, uintptr and string)
and types which implement error or Stringer interfaces are
supported with other types sorted according to the
reflect.Value.String() output which guarantees display
stability. Natural map order is used by default.
- ContinueOnMethod
Enables recursion into types after invoking error and Stringer interface
methods. Recursion after method invocation is disabled by default.
* SpewKeys
Specifies that, as a last resort attempt, map keys should be
spewed to strings and sorted by those strings. This is only
considered if SortKeys is true.
- SortKeys
Specifies map keys should be sorted before being printed. Use
this to have a more deterministic, diffable output. Note that
only native types (bool, int, uint, floats, uintptr and string)
and types which implement error or Stringer interfaces are
supported with other types sorted according to the
reflect.Value.String() output which guarantees display
stability. Natural map order is used by default.
Dump Usage
- SpewKeys
Specifies that, as a last resort attempt, map keys should be
spewed to strings and sorted by those strings. This is only
considered if SortKeys is true.
# Dump Usage
Simply call spew.Dump with a list of variables you want to dump:
@@ -133,7 +136,7 @@ A third option is to call spew.Sdump to get the formatted output as a string:
str := spew.Sdump(myVar1, myVar2, ...)
Sample Dump Output
# Sample Dump Output
See the Dump example for details on the setup of the types and variables being
shown here.
@@ -150,13 +153,14 @@ shown here.
Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
command as shown.
([]uint8) (len=32 cap=32) {
00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
00000020 31 32 |12|
}
Custom Formatter
# Custom Formatter
Spew provides a custom formatter that implements the fmt.Formatter interface
so that it integrates cleanly with standard fmt package printing functions. The
@@ -170,7 +174,7 @@ standard fmt package for formatting. In addition, the custom formatter ignores
the width and precision arguments (however they will still work on the format
specifiers not handled by the custom formatter).
Custom Formatter Usage
# Custom Formatter Usage
The simplest way to make use of the spew custom formatter is to call one of the
convenience functions such as spew.Printf, spew.Println, or spew.Printf. The
@@ -184,15 +188,17 @@ functions have syntax you are most likely already familiar with:
See the Index for the full list convenience functions.
Sample Formatter Output
# Sample Formatter Output
Double pointer to a uint8:
%v: <**>5
%+v: <**>(0xf8400420d0->0xf8400420c8)5
%#v: (**uint8)5
%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
Pointer to circular struct with a uint8 field and a pointer to itself:
%v: <*>{1 <*><shown>}
%+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
%#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
@@ -201,7 +207,7 @@ Pointer to circular struct with a uint8 field and a pointer to itself:
See the Printf example for details on the setup of variables being shown
here.
Errors
# Errors
Since it is possible for custom Stringer/error interfaces to panic, spew
detects them and handles them internally by printing the panic information
@@ -488,15 +488,15 @@ pointer addresses used to indirect to the final value. It provides the
following features over the built-in printing facilities provided by the fmt
package:
* Pointers are dereferenced and followed
* Circular data structures are detected and handled properly
* Custom Stringer/error interfaces are optionally invoked, including
on unexported types
* Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
* Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom Stringer/error interfaces are optionally invoked, including
on unexported types
- Custom types which only implement the Stringer/error interfaces via
a pointer receiver are optionally invoked when passing non-pointer
variables
- Byte arrays and slices are dumped like the hexdump -C command which
includes offsets, byte values in hex, and ASCII output
The configuration options are controlled by an exported package global,
spew.Config. See ConfigState for options documentation.
+3 -3
View File
@@ -1,4 +1,4 @@
// Package require implements the same assertions as the `assert` package but
// Package require implements the same assertions as the assert package but
// stops test execution when a test fails.
//
// # Example Usage
@@ -21,8 +21,8 @@
//
// # Assertions
//
// The `require` package have same global functions as in the `assert` package,
// but instead of returning a boolean result they call `t.FailNow()`.
// The require package have same global functions as in the assert package,
// but instead of returning a boolean result they call [testing.T.FailNow].
// A consequence of this is that it must be called from the goroutine running
// the test function, not from other goroutines created during the test.
//
+49 -53
View File
@@ -180,7 +180,7 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i
t.FailNow()
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -195,7 +195,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
t.FailNow()
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -295,7 +295,7 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
t.FailNow()
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// require.Error(t, err)
@@ -333,8 +333,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
t.FailNow()
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// require.ErrorContains(t, err, expectedErrorSubString)
@@ -348,8 +348,8 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
t.FailNow()
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// require.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
@@ -387,7 +387,7 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface
t.FailNow()
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// require.Errorf(t, err, "error message %s", "formatted")
@@ -429,7 +429,7 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// require.EventuallyWithT(t, func(c *require.CollectT) {
// require.EventuallyWithT(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// require.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
@@ -457,10 +457,10 @@ func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitF
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// require.EventuallyWithTf(t, func(c *require.CollectT, "error message %s", "formatted") {
// require.EventuallyWithTf(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// require.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -671,8 +671,6 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in
// body that contains a string.
//
// require.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -687,8 +685,6 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s
// body that contains a string.
//
// require.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -703,8 +699,6 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url
// body that does not contain a string.
//
// require.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -719,8 +713,6 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur
// body that does not contain a string.
//
// require.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -734,8 +726,6 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u
// HTTPError asserts that a specified handler returns an error status code.
//
// require.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -749,8 +739,6 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPErrorf asserts that a specified handler returns an error status code.
//
// require.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -764,8 +752,6 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPRedirect asserts that a specified handler returns a redirect status code.
//
// require.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -779,8 +765,6 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin
// HTTPRedirectf asserts that a specified handler returns a redirect status code.
//
// require.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -794,8 +778,6 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri
// HTTPStatusCode asserts that a specified handler returns a specified status code.
//
// require.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -809,8 +791,6 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url str
// HTTPStatusCodef asserts that a specified handler returns a specified status code.
//
// require.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -824,8 +804,6 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st
// HTTPSuccess asserts that a specified handler returns a success status code.
//
// require.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -839,8 +817,6 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string
// HTTPSuccessf asserts that a specified handler returns a success status code.
//
// require.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1385,12 +1361,11 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) {
t.FailNow()
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if require.NoError(t, err) {
// require.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// require.NoError(t, err)
// require.Equal(t, expectedObj, actualObj)
func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1401,12 +1376,11 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
t.FailNow()
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if require.NoErrorf(t, err, "error message %s", "formatted") {
// require.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// require.NoErrorf(t, err, "error message %s", "formatted")
// require.Equal(t, expectedObj, actualObj)
func NoErrorf(t TestingT, err error, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1515,9 +1489,8 @@ func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg str
// NotEmpty asserts that the specified object is NOT [Empty].
//
// if require.NotEmpty(t, obj) {
// require.Equal(t, "two", obj[1])
// }
// require.NotEmpty(t, obj)
// require.Equal(t, "two", obj[1])
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1530,9 +1503,8 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// NotEmptyf asserts that the specified object is NOT [Empty].
//
// if require.NotEmptyf(t, obj, "error message %s", "formatted") {
// require.Equal(t, "two", obj[1])
// }
// require.NotEmptyf(t, obj, "error message %s", "formatted")
// require.Equal(t, "two", obj[1])
func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2135,7 +2107,19 @@ func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time,
t.FailNow()
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// require.YAMLEq(t, expected, actual)
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2146,7 +2130,19 @@ func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
t.FailNow()
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// require.YAMLEqf(t, expected, actual, "error message %s", "formatted")
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
+1 -1
View File
@@ -1,4 +1,4 @@
{{ replace .Comment "assert." "require."}}
{{.CommentRequire}}
func {{.DocInfo.Name}}(t TestingT, {{.Params}}) {
if h, ok := t.(tHelper); ok { h.Helper() }
if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return }
+48 -52
View File
@@ -147,7 +147,7 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs
Equal(a.t, expected, actual, msgAndArgs...)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// EqualError asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -159,7 +159,7 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...
EqualError(a.t, theError, errString, msgAndArgs...)
}
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
@@ -241,7 +241,7 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string
Equalf(a.t, expected, actual, msg, args...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
// Error asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Error(err)
@@ -270,8 +270,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ..
ErrorAsf(a.t, err, target, msg, args...)
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContains asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContains(err, expectedErrorSubString)
@@ -282,8 +282,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs .
ErrorContains(a.t, theError, contains, msgAndArgs...)
}
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
// error) and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted")
@@ -312,7 +312,7 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter
ErrorIsf(a.t, err, target, msg, args...)
}
// Errorf asserts that a function returned an error (i.e. not `nil`).
// Errorf asserts that a function returned a non-nil error (ie. an error).
//
// actualObj, err := SomeFunction()
// a.Errorf(err, "error message %s", "formatted")
@@ -373,10 +373,10 @@ func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), w
// time.Sleep(8*time.Second)
// externalValue = true
// }()
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// a.EventuallyWithTf(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -539,8 +539,6 @@ func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args .
// body that contains a string.
//
// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -552,8 +550,6 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u
// body that contains a string.
//
// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -565,8 +561,6 @@ func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string,
// body that does not contain a string.
//
// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -578,8 +572,6 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string
// body that does not contain a string.
//
// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -590,8 +582,6 @@ func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method strin
// HTTPError asserts that a specified handler returns an error status code.
//
// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -602,8 +592,6 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri
// HTTPErrorf asserts that a specified handler returns an error status code.
//
// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -614,8 +602,6 @@ func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url str
// HTTPRedirect asserts that a specified handler returns a redirect status code.
//
// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -626,8 +612,6 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s
// HTTPRedirectf asserts that a specified handler returns a redirect status code.
//
// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -638,8 +622,6 @@ func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url
// HTTPStatusCode asserts that a specified handler returns a specified status code.
//
// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -650,8 +632,6 @@ func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url
// HTTPStatusCodef asserts that a specified handler returns a specified status code.
//
// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -662,8 +642,6 @@ func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, ur
// HTTPSuccess asserts that a specified handler returns a success status code.
//
// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -674,8 +652,6 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st
// HTTPSuccessf asserts that a specified handler returns a success status code.
//
// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1097,12 +1073,11 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{})
NoDirExistsf(a.t, path, msg, args...)
}
// NoError asserts that a function returned no error (i.e. `nil`).
// NoError asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoError(err) {
// assert.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// a.NoError(err)
// a.Equal(expectedObj, actualObj)
func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1110,12 +1085,11 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) {
NoError(a.t, err, msgAndArgs...)
}
// NoErrorf asserts that a function returned no error (i.e. `nil`).
// NoErrorf asserts that a function returned a nil error (ie. no error).
//
// actualObj, err := SomeFunction()
// if a.NoErrorf(err, "error message %s", "formatted") {
// assert.Equal(t, expectedObj, actualObj)
// }
// actualObj, err := SomeFunction()
// a.NoErrorf(err, "error message %s", "formatted")
// a.Equal(expectedObj, actualObj)
func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1203,9 +1177,8 @@ func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg
// NotEmpty asserts that the specified object is NOT [Empty].
//
// if a.NotEmpty(obj) {
// assert.Equal(t, "two", obj[1])
// }
// a.NotEmpty(obj)
// a.Equal("two", obj[1])
func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1215,9 +1188,8 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) {
// NotEmptyf asserts that the specified object is NOT [Empty].
//
// if a.NotEmptyf(obj, "error message %s", "formatted") {
// assert.Equal(t, "two", obj[1])
// }
// a.NotEmptyf(obj, "error message %s", "formatted")
// a.Equal("two", obj[1])
func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1691,7 +1663,19 @@ func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Ti
WithinRangef(a.t, actual, start, end, msg, args...)
}
// YAMLEq asserts that two YAML strings are equivalent.
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEq(expected, actual)
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1699,7 +1683,19 @@ func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interf
YAMLEq(a.t, expected, actual, msgAndArgs...)
}
// YAMLEqf asserts that two YAML strings are equivalent.
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
//
// expected := `---
// key: value
// ---
// key: this is a second document, it is not evaluated
// `
// actual := `---
// key: value
// ---
// key: this is a subsequent document, it is not evaluated
// `
// a.YAMLEqf(expected, actual, "error message %s", "formatted")
func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1,4 +1,4 @@
{{.CommentWithoutT "a"}}
{{.CommentRequireWithoutT "a"}}
func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) {
if h, ok := a.t.(tHelper); ok { h.Helper() }
{{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
+4 -4
View File
@@ -12,18 +12,18 @@ type tHelper = interface {
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
// for table driven tests.
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{})
type ComparisonAssertionFunc = func(TestingT, interface{}, interface{}, ...interface{})
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
// for table driven tests.
type ValueAssertionFunc func(TestingT, interface{}, ...interface{})
type ValueAssertionFunc = func(TestingT, interface{}, ...interface{})
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
// for table driven tests.
type BoolAssertionFunc func(TestingT, bool, ...interface{})
type BoolAssertionFunc = func(TestingT, bool, ...interface{})
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{})
type ErrorAssertionFunc = func(TestingT, error, ...interface{})
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs"
+4 -8
View File
@@ -23,9 +23,6 @@ github.com/aymerick/douceur/parser
# github.com/cespare/xxhash/v2 v2.3.0
## explicit; go 1.11
github.com/cespare/xxhash/v2
# github.com/davecgh/go-spew v1.1.1
## explicit
github.com/davecgh/go-spew/spew
# github.com/dghubble/oauth1 v0.7.3
## explicit; go 1.19
github.com/dghubble/oauth1
@@ -82,7 +79,7 @@ github.com/go-pkgz/repeater/strategy
# github.com/go-pkgz/repeater/v2 v2.2.0
## explicit; go 1.23
github.com/go-pkgz/repeater/v2
# github.com/go-pkgz/rest v1.22.0
# github.com/go-pkgz/rest v1.24.0
## explicit; go 1.24.0
github.com/go-pkgz/rest
github.com/go-pkgz/rest/logger
@@ -146,9 +143,6 @@ github.com/microcosm-cc/bluemonday/css
# github.com/montanaflynn/stats v0.9.0
## explicit; go 1.13
github.com/montanaflynn/stats
# github.com/pmezard/go-difflib v1.0.0
## explicit
github.com/pmezard/go-difflib/difflib
# github.com/redis/go-redis/v9 v9.21.0
## explicit; go 1.24
github.com/redis/go-redis/v9
@@ -187,10 +181,12 @@ github.com/slack-go/slack/internal/backoff
github.com/slack-go/slack/internal/errorsx
github.com/slack-go/slack/internal/timex
github.com/slack-go/slack/slackutilsx
# github.com/stretchr/testify v1.11.1
# github.com/stretchr/testify v1.12.0
## explicit; go 1.17
github.com/stretchr/testify/assert
github.com/stretchr/testify/assert/yaml
github.com/stretchr/testify/internal/difflib
github.com/stretchr/testify/internal/spew
github.com/stretchr/testify/require
# github.com/xdg-go/pbkdf2 v1.0.0
## explicit; go 1.9
@@ -1,33 +0,0 @@
---
worth: yes
where: backend/app/rest/api/middleware.go:127
added: 2026-08-18
---
# corsMiddleware panics at boot once go-pkgz/rest is bumped past v1.22.0
`corsMiddleware` passes `R.CorsAllowedOrigins("*")` together with `R.CorsAllowCredentials(true)`
(lines 128 and 132). go-pkgz/rest#52 makes `rest.CORS` panic at construction on exactly that
combination, so the next bump of `github.com/go-pkgz/rest` past the pinned `v1.22.0`
(`backend/go.mod:16`) crashes remark42 on startup, not at request time.
The fix is one option:
```go
R.CorsAllowedOrigins("*"),
R.CorsAllowCredentials(true),
R.CorsUnsafeAnyOriginWithCredentials(true),
```
It cannot be added before the bump, since the option does not exist in v1.22.0. So this is bump and
edit in one commit, in either order within that commit, and it will not compile split across two.
Why the wildcard stays rather than the origins being enumerated: remark42 serves a comment widget
embedded on arbitrary third-party sites, so the set of origins is not knowable. The upstream default
is right for a normal service and wrong here, which is why the escape hatch was asked for instead of
accepting the panic. The named consequence stands and is worth re-reading when this is touched: any
site a signed-in user visits can read authenticated responses, so state-changing requests must keep
being protected by something other than the origin (`X-XSRF-Token` today).
Surfaced reviewing go-pkgz/rest#52. The unconditional panic in the original version of that PR was
pushed back on precisely because remark42 had no way to comply; `CorsUnsafeAnyOriginWithCredentials`
exists as a result.