From 73ddbed1b20d9a55d6be2cc7ba4c345087e302be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 12 Jan 2026 19:30:10 +0000 Subject: [PATCH] chore(deps): bump github.com/go-resty/resty/v2 from 2.7.0 to 2.17.1 Bumps [github.com/go-resty/resty/v2](https://github.com/go-resty/resty) from 2.7.0 to 2.17.1. - [Release notes](https://github.com/go-resty/resty/releases) - [Commits](https://github.com/go-resty/resty/compare/v2.7.0...v2.17.1) --- updated-dependencies: - dependency-name: github.com/go-resty/resty/v2 dependency-version: 2.17.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 16 +- go.sum | 33 +- .../github.com/go-resty/resty/v2/.gitignore | 3 +- .../github.com/go-resty/resty/v2/BUILD.bazel | 17 +- vendor/github.com/go-resty/resty/v2/LICENSE | 2 +- vendor/github.com/go-resty/resty/v2/README.md | 96 +- vendor/github.com/go-resty/resty/v2/WORKSPACE | 8 +- vendor/github.com/go-resty/resty/v2/client.go | 1067 +++++++++++------ vendor/github.com/go-resty/resty/v2/digest.go | 327 +++++ .../go-resty/resty/v2/middleware.go | 412 ++++--- .../github.com/go-resty/resty/v2/redirect.go | 47 +- .../github.com/go-resty/resty/v2/request.go | 871 +++++++++----- .../github.com/go-resty/resty/v2/response.go | 64 +- vendor/github.com/go-resty/resty/v2/resty.go | 8 +- vendor/github.com/go-resty/resty/v2/retry.go | 58 +- .../go-resty/resty/v2/shellescape/BUILD.bazel | 14 + .../resty/v2/shellescape/shellescape.go | 40 + vendor/github.com/go-resty/resty/v2/trace.go | 52 +- .../github.com/go-resty/resty/v2/transport.go | 5 +- .../go-resty/resty/v2/transport112.go | 3 +- .../go-resty/resty/v2/transport_js.go | 17 + .../go-resty/resty/v2/transport_other.go | 17 + vendor/github.com/go-resty/resty/v2/util.go | 102 +- .../github.com/go-resty/resty/v2/util_curl.go | 78 ++ vendor/golang.org/x/net/http2/http2.go | 2 - vendor/golang.org/x/sys/unix/mkerrors.sh | 3 + .../golang.org/x/sys/unix/syscall_darwin.go | 56 +- vendor/golang.org/x/sys/unix/zerrors_linux.go | 44 +- .../x/sys/unix/zerrors_linux_386.go | 2 + .../x/sys/unix/zerrors_linux_amd64.go | 2 + .../x/sys/unix/zerrors_linux_arm.go | 2 + .../x/sys/unix/zerrors_linux_arm64.go | 2 + .../x/sys/unix/zerrors_linux_loong64.go | 2 + .../x/sys/unix/zerrors_linux_mips.go | 2 + .../x/sys/unix/zerrors_linux_mips64.go | 2 + .../x/sys/unix/zerrors_linux_mips64le.go | 2 + .../x/sys/unix/zerrors_linux_mipsle.go | 2 + .../x/sys/unix/zerrors_linux_ppc.go | 2 + .../x/sys/unix/zerrors_linux_ppc64.go | 2 + .../x/sys/unix/zerrors_linux_ppc64le.go | 2 + .../x/sys/unix/zerrors_linux_riscv64.go | 2 + .../x/sys/unix/zerrors_linux_s390x.go | 2 + .../x/sys/unix/zerrors_linux_sparc64.go | 2 + .../x/sys/unix/zsysnum_linux_386.go | 1 + .../x/sys/unix/zsysnum_linux_amd64.go | 1 + .../x/sys/unix/zsysnum_linux_arm.go | 1 + .../x/sys/unix/zsysnum_linux_arm64.go | 1 + .../x/sys/unix/zsysnum_linux_loong64.go | 1 + .../x/sys/unix/zsysnum_linux_mips.go | 1 + .../x/sys/unix/zsysnum_linux_mips64.go | 1 + .../x/sys/unix/zsysnum_linux_mips64le.go | 1 + .../x/sys/unix/zsysnum_linux_mipsle.go | 1 + .../x/sys/unix/zsysnum_linux_ppc.go | 1 + .../x/sys/unix/zsysnum_linux_ppc64.go | 1 + .../x/sys/unix/zsysnum_linux_ppc64le.go | 1 + .../x/sys/unix/zsysnum_linux_riscv64.go | 1 + .../x/sys/unix/zsysnum_linux_s390x.go | 1 + .../x/sys/unix/zsysnum_linux_sparc64.go | 1 + vendor/golang.org/x/sys/unix/ztypes_linux.go | 37 +- .../golang.org/x/sys/unix/ztypes_linux_386.go | 30 +- .../x/sys/unix/ztypes_linux_amd64.go | 28 +- .../golang.org/x/sys/unix/ztypes_linux_arm.go | 32 +- .../x/sys/unix/ztypes_linux_arm64.go | 28 +- .../x/sys/unix/ztypes_linux_loong64.go | 28 +- .../x/sys/unix/ztypes_linux_mips.go | 30 +- .../x/sys/unix/ztypes_linux_mips64.go | 28 +- .../x/sys/unix/ztypes_linux_mips64le.go | 28 +- .../x/sys/unix/ztypes_linux_mipsle.go | 30 +- .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 32 +- .../x/sys/unix/ztypes_linux_ppc64.go | 28 +- .../x/sys/unix/ztypes_linux_ppc64le.go | 28 +- .../x/sys/unix/ztypes_linux_riscv64.go | 28 +- .../x/sys/unix/ztypes_linux_s390x.go | 28 +- .../x/sys/unix/ztypes_linux_sparc64.go | 28 +- vendor/golang.org/x/term/term_windows.go | 4 +- vendor/golang.org/x/term/terminal.go | 9 +- vendor/golang.org/x/time/LICENSE | 4 +- vendor/golang.org/x/time/rate/rate.go | 47 +- vendor/golang.org/x/time/rate/sometimes.go | 4 +- .../x/tools/go/ast/inspector/typeof.go | 1 - vendor/modules.txt | 21 +- 81 files changed, 2754 insertions(+), 1314 deletions(-) create mode 100644 vendor/github.com/go-resty/resty/v2/digest.go create mode 100644 vendor/github.com/go-resty/resty/v2/shellescape/BUILD.bazel create mode 100644 vendor/github.com/go-resty/resty/v2/shellescape/shellescape.go create mode 100644 vendor/github.com/go-resty/resty/v2/transport_js.go create mode 100644 vendor/github.com/go-resty/resty/v2/transport_other.go create mode 100644 vendor/github.com/go-resty/resty/v2/util_curl.go diff --git a/go.mod b/go.mod index 0d224fee05..b06119dfdf 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/fujiwara/shapeio v1.0.0 github.com/gertd/go-pluralize v0.2.0 github.com/gliderlabs/ssh v0.3.5 - github.com/go-resty/resty/v2 v2.7.0 + github.com/go-resty/resty/v2 v2.17.1 github.com/google/go-containerregistry v0.20.6 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.0 @@ -52,9 +52,9 @@ require ( github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.10 github.com/vmware-labs/yaml-jsonpath v0.3.2 - golang.org/x/crypto v0.40.0 - golang.org/x/net v0.42.0 - golang.org/x/text v0.27.0 + golang.org/x/crypto v0.41.0 + golang.org/x/net v0.43.0 + golang.org/x/text v0.28.0 google.golang.org/grpc v1.74.2 google.golang.org/protobuf v1.36.6 gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -195,10 +195,10 @@ require ( go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect golang.org/x/oauth2 v0.30.0 // indirect golang.org/x/sync v0.16.0 // indirect - golang.org/x/sys v0.34.0 // indirect - golang.org/x/term v0.33.0 // indirect - golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.34.0 // indirect + golang.org/x/sys v0.35.0 // indirect + golang.org/x/term v0.34.0 // indirect + golang.org/x/time v0.12.0 // indirect + golang.org/x/tools v0.35.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a // indirect gopkg.in/inf.v0 v0.9.1 // indirect diff --git a/go.sum b/go.sum index 5930af4bf0..a9dc57f970 100644 --- a/go.sum +++ b/go.sum @@ -191,8 +191,8 @@ github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2Kv github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= -github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= +github.com/go-resty/resty/v2 v2.17.1 h1:x3aMpHK1YM9e4va/TMDRlusDDoZiQ+ViDu/WpA6xTM4= +github.com/go-resty/resty/v2 v2.17.1/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= @@ -611,8 +611,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20220826181053-bd7e27e6170d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= -golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -635,11 +635,10 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= -golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= -golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -681,27 +680,27 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= -golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg= -golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0= +golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4= +golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= -golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -711,8 +710,8 @@ golang.org/x/tools v0.0.0-20190729092621-ff9f1409240a/go.mod h1:jcCCGcm9btYwXyDq golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= -golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= +golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= +golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/github.com/go-resty/resty/v2/.gitignore b/vendor/github.com/go-resty/resty/v2/.gitignore index 9e856bd484..7542ac89e3 100644 --- a/vendor/github.com/go-resty/resty/v2/.gitignore +++ b/vendor/github.com/go-resty/resty/v2/.gitignore @@ -26,5 +26,6 @@ _testmain.go coverage.out coverage.txt -# Exclude intellij IDE folders +# Exclude IDE folders .idea/* +.vscode/* diff --git a/vendor/github.com/go-resty/resty/v2/BUILD.bazel b/vendor/github.com/go-resty/resty/v2/BUILD.bazel index 03bb44c3ed..7248abc506 100644 --- a/vendor/github.com/go-resty/resty/v2/BUILD.bazel +++ b/vendor/github.com/go-resty/resty/v2/BUILD.bazel @@ -1,5 +1,5 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") load("@bazel_gazelle//:def.bzl", "gazelle") +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") # gazelle:prefix github.com/go-resty/resty/v2 # gazelle:go_naming_convention import_alias @@ -9,6 +9,7 @@ go_library( name = "resty", srcs = [ "client.go", + "digest.go", "middleware.go", "redirect.go", "request.go", @@ -18,11 +19,17 @@ go_library( "trace.go", "transport.go", "transport112.go", + "transport_js.go", + "transport_other.go", "util.go", + "util_curl.go", ], importpath = "github.com/go-resty/resty/v2", visibility = ["//visibility:public"], - deps = ["@org_golang_x_net//publicsuffix:go_default_library"], + deps = [ + "//shellescape", + "@org_golang_x_net//publicsuffix:go_default_library", + ], ) go_test( @@ -31,6 +38,7 @@ go_test( "client_test.go", "context_test.go", "example_test.go", + "middleware_test.go", "request_test.go", "resty_test.go", "retry_test.go", @@ -38,7 +46,10 @@ go_test( ], data = glob([".testdata/*"]), embed = [":resty"], - deps = ["@org_golang_x_net//proxy:go_default_library"], + deps = [ + "@org_golang_x_net//proxy:go_default_library", + "@org_golang_x_time//rate:go_default_library", + ], ) alias( diff --git a/vendor/github.com/go-resty/resty/v2/LICENSE b/vendor/github.com/go-resty/resty/v2/LICENSE index 27326a653c..de30fea8f2 100644 --- a/vendor/github.com/go-resty/resty/v2/LICENSE +++ b/vendor/github.com/go-resty/resty/v2/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015-2021 Jeevanandam M., https://myjeeva.com +Copyright (c) 2015-2024 Jeevanandam M., https://myjeeva.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/go-resty/resty/v2/README.md b/vendor/github.com/go-resty/resty/v2/README.md index 8ec6518286..21bf8d1241 100644 --- a/vendor/github.com/go-resty/resty/v2/README.md +++ b/vendor/github.com/go-resty/resty/v2/README.md @@ -4,16 +4,12 @@

Features section describes in detail about Resty capabilities

-

Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

-

-

-

Resty Communication Channels

-

Chat on Gitter - Resty Community Twitter @go_resty

+

Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

## News - * v2.7.0 [released](https://github.com/go-resty/resty/releases/tag/v2.7.0) and tagged on Nov 03, 2021. + * v2.17.1 [released](https://github.com/go-resty/resty/releases/tag/v2.17.1) and tagged on Dec 15, 2025. * v2.0.0 [released](https://github.com/go-resty/resty/releases/tag/v2.0.0) and tagged on Jul 16, 2019. * v1.12.0 [released](https://github.com/go-resty/resty/releases/tag/v1.12.0) and tagged on Feb 27, 2019. * v1.0 released and tagged on Sep 25, 2017. - Resty's first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years since first release. I'm very thankful to Resty users and its [contributors](https://github.com/go-resty/resty/graphs/contributors). @@ -62,9 +58,10 @@ * goroutine concurrent safe * Resty Client trace, see [Client.EnableTrace](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.EnableTrace) and [Request.EnableTrace](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.EnableTrace) * Since v2.4.0, trace info contains a `RequestAttempt` value, and the `Request` object contains an `Attempt` attribute + * Supports on-demand CURL command generation, see [Client.EnableGenerateCurlOnDebug](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.EnableGenerateCurlOnDebug), [Request.EnableGenerateCurlOnDebug](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.EnableGenerateCurlOnDebug). It requires debug mode to be enabled. * Debug mode - clean and informative logging presentation * Gzip - Go does it automatically also resty has fallback handling too - * Works fine with `HTTP/2` and `HTTP/1.1` + * Works fine with `HTTP/2` and `HTTP/1.1`, also `HTTP/3` can be used with Resty, see this [comment](https://github.com/go-resty/resty/issues/846#issuecomment-2329696110) * [Bazel support](#bazel-support) * Easily mock Resty for testing, [for e.g.](#mocking-http-requests-using-httpmock-library) * Well tested client library @@ -86,6 +83,8 @@ #### Supported Go Versions +Recommended to use `go1.23` and above. + Initially Resty started supporting `go modules` since `v1.10.0` release. Starting Resty v2 and higher versions, it fully embraces [go modules](https://github.com/golang/go/wiki/Modules) package release. It requires a Go version capable of understanding `/vN` suffixed imports: @@ -99,8 +98,6 @@ Starting Resty v2 and higher versions, it fully embraces [go modules](https://gi Resty author also published following projects for Go Community. - * [aah framework](https://aahframework.org) - A secure, flexible, rapid Go web framework. - * [THUMBAI](https://thumbai.app) - Go Mod Repository, Go Vanity Service and Simple Proxy Server. * [go-model](https://github.com/jeevatkm/go-model) - Robust & Easy to use model mapper and utility methods for Go `struct`. @@ -108,7 +105,7 @@ Resty author also published following projects for Go Community. ```bash # Go Modules -require github.com/go-resty/resty/v2 v2.7.0 +require github.com/go-resty/resty/v2 v2.16.5 ``` ## Usage @@ -265,7 +262,7 @@ resp, err := client.R(). Post("https://myapp.com/login") // POST of raw bytes for file upload. For example: upload file to Dropbox -fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf") +fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf") // See we are not setting content-type header, since go-resty automatically detects Content-Type for you resp, err := client.R(). @@ -369,13 +366,13 @@ import jsoniter "github.com/json-iterator/go" json := jsoniter.ConfigCompatibleWithStandardLibrary -client := resty.New() -client.JSONMarshal = json.Marshal -client.JSONUnmarshal = json.Unmarshal +client := resty.New(). + SetJSONMarshaler(json.Marshal). + SetJSONUnmarshaler(json.Unmarshal) // similarly user could do for XML too with - -client.XMLMarshal -client.XMLUnmarshal +client.SetXMLMarshaler(xml.Marshal). + SetXMLUnmarshaler(xml.Unmarshal) ``` ### Multipart File(s) upload @@ -383,8 +380,8 @@ client.XMLUnmarshal #### Using io.Reader ```go -profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png") -notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt") +profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png") +notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt") // Create a Resty Client client := resty.New() @@ -475,7 +472,7 @@ resp, err := client.R(). client := resty.New() // Setting output directory path, If directory not exists then resty creates one! -// This is optional one, if you're planning using absoule path in +// This is optional one, if you're planning using absolute path in // `Request.SetOutput` and can used together. client.SetOutputDirectory("/Users/jeeva/Downloads") @@ -556,6 +553,30 @@ client.OnError(func(req *resty.Request, err error) { }) ``` +#### Generate CURL Command +>Refer: [curl_cmd_test.go](https://github.com/go-resty/resty/blob/v2/curl_cmd_test.go) + +```go +// Create a Resty Client +client := resty.New() + +resp, err := client.R(). + SetDebug(true). + EnableGenerateCurlOnDebug(). // CURL command generated when debug mode enabled with this option + SetBody(map[string]string{"name": "Alex"}). + Post("https://httpbin.org/post") + +curlCmdExecuted := resp.Request.GenerateCurlCommand() + +// Explore curl command +fmt.Println("Curl Command:\n ", curlCmdExecuted+"\n") + +/* Output +Curl Command: + curl -X POST -H 'Content-Type: application/json' -H 'User-Agent: go-resty/2.14.0 (https://github.com/go-resty/resty)' -d '{"name":"Alex"}' https://httpbin.org/post +*/ +``` + #### Redirect Policy Resty provides few ready to use redirect policy(s) also it supports multiple policies together. @@ -635,7 +656,7 @@ client.SetCertificates(cert1, cert2, cert3) ```go // Custom Root certificates from string -// You can pass you certificates throught env variables as strings +// You can pass you certificates through env variables as strings // you can add one or more root certificates, its get appended client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") @@ -654,7 +675,7 @@ if err != nil { client.SetCertificates(cert1, cert2, cert3) ``` -#### Proxy Settings - Client as well as at Request Level +#### Proxy Settings Default `Go` supports Proxy via environment variable `HTTP_PROXY`. Resty provides support via `SetProxy` & `RemoveProxy`. Choose as per your need. @@ -700,8 +721,9 @@ client. }) ``` -Above setup will result in resty retrying requests returned non nil error up to -3 times with delay increased after each attempt. +By default, resty will retry requests that return a non-nil error during execution. +Therefore, the above setup will result in resty retrying requests with non-nil errors up to 3 times, +with the delay increasing after each attempt. You can optionally provide client with [custom retry conditions](https://pkg.go.dev/github.com/go-resty/resty/v2#RetryConditionFunc): @@ -718,10 +740,26 @@ client.AddRetryCondition( ) ``` -Above example will make resty retry requests ended with `429 Too Many Requests` -status code. +The above example will make resty retry requests that end with a `429 Too Many Requests` status code. +It's important to note that when you specify conditions using `AddRetryCondition`, +it will override the default retry behavior, which retries on errors encountered during the request. +If you want to retry on errors encountered during the request, similar to the default behavior, +you'll need to configure it as follows: + +```go +// Create a Resty Client +client := resty.New() + +client.AddRetryCondition( + func(r *resty.Response, err error) bool { + // Including "err != nil" emulates the default retry behavior for errors encountered during the request. + return err != nil || r.StatusCode() == http.StatusTooManyRequests + }, +) +``` Multiple retry conditions can be added. +Note that if multiple conditions are specified, a retry will occur if any of the conditions are met. It is also possible to use `resty.Backoff(...)` to get arbitrary retry scenarios implemented. [Reference](retry_test.go). @@ -778,7 +816,7 @@ client.SetTimeout(1 * time.Minute) // You can override all below settings and options at request level if you want to //-------------------------------------------------------------------------------- // Host URL for all request. So you can use relative URL in the request -client.SetHostURL("http://httpbin.org") +client.SetBaseURL("http://httpbin.org") // Headers for all request client.SetHeader("Accept", "application/json") @@ -803,7 +841,7 @@ client.SetCookies(cookies) client.SetQueryParam("user_id", "00001") client.SetQueryParams(map[string]string{ // sample of those who use this manner "api_key": "api-key-here", - "api_secert": "api-secert", + "api_secret": "api-secret", }) client.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") @@ -842,10 +880,10 @@ client := resty.New() // Set the previous transport that we created, set the scheme of the communication to the // socket and set the unixSocket as the HostURL. -client.SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket) +client.SetTransport(&transport).SetScheme("http").SetBaseURL(unixSocket) // No need to write the host's URL on the request, just the path. -client.R().Get("/index.html") +client.R().Get("http://localhost/index.html") ``` #### Bazel Support diff --git a/vendor/github.com/go-resty/resty/v2/WORKSPACE b/vendor/github.com/go-resty/resty/v2/WORKSPACE index 9ef03e95a4..504de14582 100644 --- a/vendor/github.com/go-resty/resty/v2/WORKSPACE +++ b/vendor/github.com/go-resty/resty/v2/WORKSPACE @@ -4,10 +4,10 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", - sha256 = "69de5c704a05ff37862f7e0f5534d4f479418afc21806c887db544a316f3cb6b", + sha256 = "80a98277ad1311dacd837f9b16db62887702e9f1d1c4c9f796d0121a46c8e184", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.27.0/rules_go-v0.27.0.tar.gz", - "https://github.com/bazelbuild/rules_go/releases/download/v0.27.0/rules_go-v0.27.0.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", + "https://github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", ], ) @@ -24,7 +24,7 @@ load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_depe go_rules_dependencies() -go_register_toolchains(version = "1.16") +go_register_toolchains(version = "1.19") load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") diff --git a/vendor/github.com/go-resty/resty/v2/client.go b/vendor/github.com/go-resty/resty/v2/client.go index 1a03efa375..ca0f8af89c 100644 --- a/vendor/github.com/go-resty/resty/v2/client.go +++ b/vendor/github.com/go-resty/resty/v2/client.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,10 +14,10 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "net/http" "net/url" + "os" "reflect" "regexp" "strings" @@ -55,13 +55,15 @@ var ( hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length") hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding") hdrLocationKey = http.CanonicalHeaderKey("Location") + hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization") + hdrWwwAuthenticateKey = http.CanonicalHeaderKey("WWW-Authenticate") plainTextType = "text/plain; charset=utf-8" jsonContentType = "application/json" formContentType = "application/x-www-form-urlencoded" - jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`) - xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`) + jsonCheck = regexp.MustCompile(`(?i:(application|text)/(.*json.*)(;|$))`) + xmlCheck = regexp.MustCompile(`(?i:(application|text)/(.*xml.*)(;|$))`) hdrUserAgentValue = "go-resty/" + Version + " (https://github.com/go-resty/resty)" bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} @@ -85,19 +87,23 @@ type ( // ErrorHook type is for reacting to request errors, called after all retries were attempted ErrorHook func(*Request, error) + + // SuccessHook type is for reacting to request success + SuccessHook func(*Client, *Response) ) -// Client struct is used to create Resty client with client level settings, -// these settings are applicable to all the request raised from the client. +// Client struct is used to create a Resty client with client-level settings, +// these settings apply to all the requests raised from the client. // -// Resty also provides an options to override most of the client settings -// at request level. +// Resty also provides an option to override most of the client settings +// at [Request] level. type Client struct { BaseURL string HostURL string // Deprecated: use BaseURL instead. To be removed in v3.0.0 release. QueryParam url.Values FormData url.Values PathParams map[string]string + RawPathParams map[string]string Header http.Header UserInfo *User Token string @@ -113,6 +119,7 @@ type Client struct { RetryConditions []RetryConditionFunc RetryHooks []OnRetryFunc RetryAfter RetryAfterFunc + RetryResetReaders bool JSONMarshal func(v interface{}) ([]byte, error) JSONUnmarshal func(data []byte, v interface{}) error XMLMarshal func(v interface{}) ([]byte, error) @@ -121,25 +128,34 @@ type Client struct { // HeaderAuthorizationKey is used to set/access Request Authorization header // value when `SetAuthToken` option is used. HeaderAuthorizationKey string - - jsonEscapeHTML bool - setContentLength bool - closeConnection bool - notParseResponse bool - trace bool - debugBodySizeLimit int64 - outputDirectory string - scheme string - log Logger - httpClient *http.Client - proxyURL *url.URL - beforeRequest []RequestMiddleware - udBeforeRequest []RequestMiddleware - preReqHook PreRequestHook - afterResponse []ResponseMiddleware - requestLog RequestLogCallback - responseLog ResponseLogCallback - errorHooks []ErrorHook + ResponseBodyLimit int + + jsonEscapeHTML bool + setContentLength bool + closeConnection bool + notParseResponse bool + trace bool + debugBodySizeLimit int64 + outputDirectory string + scheme string + log Logger + httpClient *http.Client + proxyURL *url.URL + beforeRequest []RequestMiddleware + udBeforeRequest []RequestMiddleware + udBeforeRequestLock *sync.RWMutex + preReqHook PreRequestHook + successHooks []SuccessHook + afterResponse []ResponseMiddleware + afterResponseLock *sync.RWMutex + requestLog RequestLogCallback + responseLog ResponseLogCallback + errorHooks []ErrorHook + invalidHooks []ErrorHook + panicHooks []ErrorHook + rateLimiter RateLimiter + generateCurlOnDebug bool + unescapeQueryParams bool } // User type is to hold an username and password information @@ -151,29 +167,29 @@ type User struct { // Client methods //___________________________________ -// SetHostURL method is to set Host URL in the client instance. It will be used with request -// raised from this client with relative URL -// // Setting HTTP address -// client.SetHostURL("http://myjeeva.com") +// SetHostURL method sets the Host URL in the client instance. It will be used with a request +// raised from this client with a relative URL // -// // Setting HTTPS address -// client.SetHostURL("https://myjeeva.com") +// // Setting HTTP address +// client.SetHostURL("http://myjeeva.com") // -// Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release. +// // Setting HTTPS address +// client.SetHostURL("https://myjeeva.com") +// +// Deprecated: use [Client.SetBaseURL] instead. To be removed in the v3.0.0 release. func (c *Client) SetHostURL(url string) *Client { c.SetBaseURL(url) return c } -// SetBaseURL method is to set Base URL in the client instance. It will be used with request -// raised from this client with relative URL -// // Setting HTTP address -// client.SetBaseURL("http://myjeeva.com") +// SetBaseURL method sets the Base URL in the client instance. It will be used with a request +// raised from this client with a relative URL // -// // Setting HTTPS address -// client.SetBaseURL("https://myjeeva.com") +// // Setting HTTP address +// client.SetBaseURL("http://myjeeva.com") // -// Since v2.7.0 +// // Setting HTTPS address +// client.SetBaseURL("https://myjeeva.com") func (c *Client) SetBaseURL(url string) *Client { c.BaseURL = strings.TrimRight(url, "/") c.HostURL = c.BaseURL @@ -181,33 +197,33 @@ func (c *Client) SetBaseURL(url string) *Client { } // SetHeader method sets a single header field and its value in the client instance. -// These headers will be applied to all requests raised from this client instance. -// Also it can be overridden at request level header options. +// These headers will be applied to all requests from this client instance. +// Also, it can be overridden by request-level header options. // -// See `Request.SetHeader` or `Request.SetHeaders`. +// See [Request.SetHeader] or [Request.SetHeaders]. // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client. -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") +// client. +// SetHeader("Content-Type", "application/json"). +// SetHeader("Accept", "application/json") func (c *Client) SetHeader(header, value string) *Client { c.Header.Set(header, value) return c } -// SetHeaders method sets multiple headers field and its values at one go in the client instance. -// These headers will be applied to all requests raised from this client instance. Also it can be +// SetHeaders method sets multiple header fields and their values at one go in the client instance. +// These headers will be applied to all requests from this client instance. Also, it can be // overridden at request level headers options. // -// See `Request.SetHeaders` or `Request.SetHeader`. +// See [Request.SetHeaders] or [Request.SetHeader]. // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client.SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) +// client.SetHeaders(map[string]string{ +// "Content-Type": "application/json", +// "Accept": "application/json", +// }) func (c *Client) SetHeaders(headers map[string]string) *Client { for h, v := range headers { c.Header.Set(h, v) @@ -215,91 +231,94 @@ func (c *Client) SetHeaders(headers map[string]string) *Client { return c } -// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. +// SetHeaderVerbatim method sets a single header field and its value verbatim in the current request. // // For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") -// -// Also you can override header value, which was set at client instance level. // -// Since v2.6.0 +// client. +// SetHeaderVerbatim("all_lowercase", "available"). +// SetHeaderVerbatim("UPPERCASE", "available") func (c *Client) SetHeaderVerbatim(header, value string) *Client { c.Header[header] = []string{value} return c } -// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. +// SetCookieJar method sets custom [http.CookieJar] in the resty client. It's a way to override the default. // -// For Example: sometimes we don't want to save cookies in api contacting, we can remove the default +// For Example, sometimes we don't want to save cookies in API mode so that we can remove the default // CookieJar in resty client. // -// client.SetCookieJar(nil) +// client.SetCookieJar(nil) func (c *Client) SetCookieJar(jar http.CookieJar) *Client { c.httpClient.Jar = jar return c } -// SetCookie method appends a single cookie in the client instance. -// These cookies will be added to all the request raised from this client instance. -// client.SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) +// SetCookie method appends a single cookie to the client instance. +// These cookies will be added to all the requests from this client instance. +// +// client.SetCookie(&http.Cookie{ +// Name:"go-resty", +// Value:"This is cookie value", +// }) func (c *Client) SetCookie(hc *http.Cookie) *Client { c.Cookies = append(c.Cookies, hc) return c } // SetCookies method sets an array of cookies in the client instance. -// These cookies will be added to all the request raised from this client instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty -// client.SetCookies(cookies) +// These cookies will be added to all the requests from this client instance. +// +// cookies := []*http.Cookie{ +// &http.Cookie{ +// Name:"go-resty-1", +// Value:"This is cookie 1 value", +// }, +// &http.Cookie{ +// Name:"go-resty-2", +// Value:"This is cookie 2 value", +// }, +// } +// +// // Setting a cookies into resty +// client.SetCookies(cookies) func (c *Client) SetCookies(cs []*http.Cookie) *Client { c.Cookies = append(c.Cookies, cs...) return c } -// SetQueryParam method sets single parameter and its value in the client instance. -// It will be formed as query string for the request. +// SetQueryParam method sets a single parameter and its value in the client instance. +// It will be formed as a query string for the request. +// +// For Example: `search=kitchen%20papers&size=large` +// +// In the URL after the `?` mark. These query params will be added to all the requests raised from +// this client instance. Also, it can be overridden at the request level. // -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from -// this client instance. Also it can be overridden at request level Query Param options. +// See [Request.SetQueryParam] or [Request.SetQueryParams]. // -// See `Request.SetQueryParam` or `Request.SetQueryParams`. -// client. -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") +// client. +// SetQueryParam("search", "kitchen papers"). +// SetQueryParam("size", "large") func (c *Client) SetQueryParam(param, value string) *Client { c.QueryParam.Set(param, value) return c } // SetQueryParams method sets multiple parameters and their values at one go in the client instance. -// It will be formed as query string for the request. +// It will be formed as a query string for the request. // -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from this -// client instance. Also it can be overridden at request level Query Param options. +// For Example: `search=kitchen%20papers&size=large` // -// See `Request.SetQueryParams` or `Request.SetQueryParam`. -// client.SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) +// In the URL after the `?` mark. These query params will be added to all the requests raised from this +// client instance. Also, it can be overridden at the request level. +// +// See [Request.SetQueryParams] or [Request.SetQueryParam]. +// +// client.SetQueryParams(map[string]string{ +// "search": "kitchen papers", +// "size": "large", +// }) func (c *Client) SetQueryParams(params map[string]string) *Client { for p, v := range params { c.SetQueryParam(p, v) @@ -307,16 +326,28 @@ func (c *Client) SetQueryParams(params map[string]string) *Client { return c } +// SetUnescapeQueryParams method sets the unescape query parameters choice for request URL. +// To prevent broken URL, resty replaces space (" ") with "+" in the query parameters. +// +// See [Request.SetUnescapeQueryParams] +// +// NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters. +func (c *Client) SetUnescapeQueryParams(unescape bool) *Client { + c.unescapeQueryParams = unescape + return c +} + // SetFormData method sets Form parameters and their values in the client instance. -// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as -// `application/x-www-form-urlencoded`. These form data will be added to all the request raised from -// this client instance. Also it can be overridden at request level form data. -// -// See `Request.SetFormData`. -// client.SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) +// It applies only to HTTP methods `POST` and `PUT`, and the request content type would be set as +// `application/x-www-form-urlencoded`. These form data will be added to all the requests raised from +// this client instance. Also, it can be overridden at the request level. +// +// See [Request.SetFormData]. +// +// client.SetFormData(map[string]string{ +// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", +// "user_id": "3455454545", +// }) func (c *Client) SetFormData(data map[string]string) *Client { for k, v := range data { c.FormData.Set(k, v) @@ -325,129 +356,213 @@ func (c *Client) SetFormData(data map[string]string) *Client { } // SetBasicAuth method sets the basic authentication header in the HTTP request. For Example: -// Authorization: Basic +// +// Authorization: Basic // // For Example: To set the header for username "go-resty" and password "welcome" -// client.SetBasicAuth("go-resty", "welcome") // -// This basic auth information gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. +// client.SetBasicAuth("go-resty", "welcome") +// +// This basic auth information is added to all requests from this client instance. +// It can also be overridden at the request level. // -// See `Request.SetBasicAuth`. +// See [Request.SetBasicAuth]. func (c *Client) SetBasicAuth(username, password string) *Client { c.UserInfo = &User{Username: username, Password: password} return c } // SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests. -// The default auth scheme is `Bearer`, it can be customized with the method `SetAuthScheme`. For Example: -// Authorization: +// The default auth scheme is `Bearer`; it can be customized with the method [Client.SetAuthScheme]. For Example: +// +// Authorization: // // For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F // -// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") +// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // -// This auth token gets added to all the requests rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. +// This auth token gets added to all the requests raised from this client instance. +// Also, it can be overridden at the request level. // -// See `Request.SetAuthToken`. +// See [Request.SetAuthToken]. func (c *Client) SetAuthToken(token string) *Client { c.Token = token return c } // SetAuthScheme method sets the auth scheme type in the HTTP request. For Example: -// Authorization: +// +// Authorization: // // For Example: To set the scheme to use OAuth // -// client.SetAuthScheme("OAuth") +// client.SetAuthScheme("OAuth") +// +// This auth scheme gets added to all the requests raised from this client instance. +// Also, it can be overridden at the request level. // -// This auth scheme gets added to all the requests rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. +// Information about auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes]. // -// Information about auth schemes can be found in RFC7235 which is linked to below -// along with the page containing the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// See [Request.SetAuthToken]. // -// See `Request.SetAuthToken`. +// [RFC 7235]: https://tools.ietf.org/html/rfc7235 +// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes func (c *Client) SetAuthScheme(scheme string) *Client { c.AuthScheme = scheme return c } -// R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc. +// SetDigestAuth method sets the Digest Access auth scheme for the client. If a server responds with 401 and sends +// a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate Authorization Header. +// +// For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life" +// +// client.SetDigestAuth("Mufasa", "Circle Of Life") +// +// Information about Digest Access Authentication can be found in [RFC 7616]. +// +// See [Request.SetDigestAuth]. +// +// [RFC 7616]: https://datatracker.ietf.org/doc/html/rfc7616 +func (c *Client) SetDigestAuth(username, password string) *Client { + oldTransport := c.httpClient.Transport + c.OnBeforeRequest(func(c *Client, _ *Request) error { + c.httpClient.Transport = &digestTransport{ + digestCredentials: digestCredentials{username, password}, + transport: oldTransport, + } + return nil + }) + c.OnAfterResponse(func(c *Client, _ *Response) error { + c.httpClient.Transport = oldTransport + return nil + }) + return c +} + +// R method creates a new request instance; it's used for Get, Post, Put, Delete, Patch, Head, Options, etc. func (c *Client) R() *Request { r := &Request{ - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - Cookies: make([]*http.Cookie, 0), - - client: c, - multipartFiles: []*File{}, - multipartFields: []*MultipartField{}, - PathParams: map[string]string{}, - jsonEscapeHTML: true, + QueryParam: url.Values{}, + FormData: url.Values{}, + Header: http.Header{}, + Cookies: make([]*http.Cookie, 0), + PathParams: map[string]string{}, + RawPathParams: map[string]string{}, + Debug: c.Debug, + AuthScheme: c.AuthScheme, + + client: c, + multipartFiles: []*File{}, + multipartFields: []*MultipartField{}, + jsonEscapeHTML: c.jsonEscapeHTML, + log: c.log, + responseBodyLimit: c.ResponseBodyLimit, + generateCurlOnDebug: c.generateCurlOnDebug, + unescapeQueryParams: c.unescapeQueryParams, } return r } -// NewRequest is an alias for method `R()`. Creates a new request instance, its used for -// Get, Post, Put, Delete, Patch, Head, Options, etc. +// NewRequest method is an alias for method `R()`. func (c *Client) NewRequest() *Request { return c.R() } -// OnBeforeRequest method appends request middleware into the before request chain. -// Its gets applied after default Resty request middlewares and before request -// been sent from Resty to host server. -// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { -// // Now you have access to Client and Request instance -// // manipulate it as per your need +// OnBeforeRequest method appends a request middleware to the before request chain. +// The user-defined middlewares are applied before the default Resty request middlewares. +// After all middlewares have been applied, the request is sent from Resty to the host server. // -// return nil // if its success otherwise return error -// }) +// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { +// // Now you have access to the Client and Request instance +// // manipulate it as per your need +// +// return nil // if its successful otherwise return error +// }) func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client { + c.udBeforeRequestLock.Lock() + defer c.udBeforeRequestLock.Unlock() + c.udBeforeRequest = append(c.udBeforeRequest, m) + return c } -// OnAfterResponse method appends response middleware into the after response chain. -// Once we receive response from host server, default Resty response middleware -// gets applied and then user assigened response middlewares applied. -// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { -// // Now you have access to Client and Response instance -// // manipulate it as per your need +// OnAfterResponse method appends response middleware to the after-response chain. +// Once we receive a response from the host server, the default Resty response middleware +// gets applied, and then the user-assigned response middleware is applied. // -// return nil // if its success otherwise return error -// }) +// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { +// // Now you have access to the Client and Response instance +// // manipulate it as per your need +// +// return nil // if its successful otherwise return error +// }) func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { + c.afterResponseLock.Lock() + defer c.afterResponseLock.Unlock() + c.afterResponse = append(c.afterResponse, m) + return c } // OnError method adds a callback that will be run whenever a request execution fails. // This is called after all retries have been attempted (if any). -// If there was a response from the server, the error will be wrapped in *ResponseError +// If there was a response from the server, the error will be wrapped in [ResponseError] // which has the last response received from the server. // -// client.OnError(func(req *resty.Request, err error) { -// if v, ok := err.(*resty.ResponseError); ok { -// // Do something with v.Response -// } -// // Log the error, increment a metric, etc... -// }) +// client.OnError(func(req *resty.Request, err error) { +// if v, ok := err.(*resty.ResponseError); ok { +// // Do something with v.Response +// } +// // Log the error, increment a metric, etc... +// }) +// +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. func (c *Client) OnError(h ErrorHook) *Client { c.errorHooks = append(c.errorHooks, h) return c } -// SetPreRequestHook method sets the given pre-request function into resty client. +// OnSuccess method adds a callback that will be run whenever a request execution +// succeeds. This is called after all retries have been attempted (if any). +// +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. +func (c *Client) OnSuccess(h SuccessHook) *Client { + c.successHooks = append(c.successHooks, h) + return c +} + +// OnInvalid method adds a callback that will be run whenever a request execution +// fails before it starts because the request is invalid. +// +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. +func (c *Client) OnInvalid(h ErrorHook) *Client { + c.invalidHooks = append(c.invalidHooks, h) + return c +} + +// OnPanic method adds a callback that will be run whenever a request execution +// panics. +// +// Out of the [Client.OnSuccess], [Client.OnError], [Client.OnInvalid], [Client.OnPanic] +// callbacks, exactly one set will be invoked for each call to [Request.Execute] that completes. +// +// If an [Client.OnSuccess], [Client.OnError], or [Client.OnInvalid] callback panics, +// then exactly one rule can be violated. +func (c *Client) OnPanic(h ErrorHook) *Client { + c.panicHooks = append(c.panicHooks, h) + return c +} + +// SetPreRequestHook method sets the given pre-request function into a resty client. // It is called right before the request is fired. // -// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for mutilple. +// NOTE: Only one pre-request hook can be registered. Use [Client.OnBeforeRequest] for multiple. func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { if c.preReqHook != nil { c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h)) @@ -456,24 +571,32 @@ func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { return c } -// SetDebug method enables the debug mode on Resty client. Client logs details of every request and response. -// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. -// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. -// client.SetDebug(true) +// SetDebug method enables the debug mode on the Resty client. The client logs details +// of every request and response. +// +// client.SetDebug(true) +// +// Also, it can be enabled at the request level for a particular request; see [Request.SetDebug]. +// - For [Request], it logs information such as HTTP verb, Relative URL path, +// Host, Headers, and Body if it has one. +// - For [Response], it logs information such as Status, Response Time, Headers, +// and Body if it has one. func (c *Client) SetDebug(d bool) *Client { c.Debug = d return c } -// SetDebugBodyLimit sets the maximum size for which the response and request body will be logged in debug mode. -// client.SetDebugBodyLimit(1000000) +// SetDebugBodyLimit sets the maximum size in bytes for which the response and +// request body will be logged in debug mode. +// +// client.SetDebugBodyLimit(1000000) func (c *Client) SetDebugBodyLimit(sl int64) *Client { c.debugBodySizeLimit = sl return c } -// OnRequestLog method used to set request log callback into Resty. Registered callback gets -// called before the resty actually logs the information. +// OnRequestLog method sets the request log callback to Resty. Registered callback gets +// called before the resty logs the information. func (c *Client) OnRequestLog(rl RequestLogCallback) *Client { if c.requestLog != nil { c.log.Warnf("Overwriting an existing on-request-log callback from=%s to=%s", @@ -483,8 +606,8 @@ func (c *Client) OnRequestLog(rl RequestLogCallback) *Client { return c } -// OnResponseLog method used to set response log callback into Resty. Registered callback gets -// called before the resty actually logs the information. +// OnResponseLog method sets the response log callback to Resty. Registered callback gets +// called before the resty logs the information. func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client { if c.responseLog != nil { c.log.Warnf("Overwriting an existing on-response-log callback from=%s to=%s", @@ -494,19 +617,21 @@ func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client { return c } -// SetDisableWarn method disables the warning message on Resty client. +// SetDisableWarn method disables the warning log message on the Resty client. +// +// For example, Resty warns users when BasicAuth is used in non-TLS mode. // -// For Example: Resty warns the user when BasicAuth used on non-TLS mode. -// client.SetDisableWarn(true) +// client.SetDisableWarn(true) func (c *Client) SetDisableWarn(d bool) *Client { c.DisableWarn = d return c } -// SetAllowGetMethodPayload method allows the GET method with payload on Resty client. +// SetAllowGetMethodPayload method allows the GET method with payload on the Resty client. // -// For Example: Resty allows the user sends request with a payload on HTTP GET method. -// client.SetAllowGetMethodPayload(true) +// For example, Resty allows the user to send a request with a payload using the HTTP GET method. +// +// client.SetAllowGetMethodPayload(true) func (c *Client) SetAllowGetMethodPayload(a bool) *Client { c.AllowGetMethodPayload = a return c @@ -514,47 +639,50 @@ func (c *Client) SetAllowGetMethodPayload(a bool) *Client { // SetLogger method sets given writer for logging Resty request and response details. // -// Compliant to interface `resty.Logger`. +// Compliant to interface [resty.Logger] func (c *Client) SetLogger(l Logger) *Client { c.log = l return c } // SetContentLength method enables the HTTP header `Content-Length` value for every request. -// By default Resty won't set `Content-Length`. -// client.SetContentLength(true) +// By default, Resty won't set `Content-Length`. +// +// client.SetContentLength(true) // -// Also you have an option to enable for particular request. See `Request.SetContentLength` +// Also, you have the option to enable a particular request. See [Request.SetContentLength] func (c *Client) SetContentLength(l bool) *Client { c.setContentLength = l return c } -// SetTimeout method sets timeout for request raised from client. -// client.SetTimeout(time.Duration(1 * time.Minute)) +// SetTimeout method sets the timeout for a request raised by the client. +// +// client.SetTimeout(time.Duration(1 * time.Minute)) func (c *Client) SetTimeout(timeout time.Duration) *Client { c.httpClient.Timeout = timeout return c } -// SetError method is to register the global or client common `Error` object into Resty. -// It is used for automatic unmarshalling if response status code is greater than 399 and -// content type either JSON or XML. Can be pointer or non-pointer. -// client.SetError(&Error{}) -// // OR -// client.SetError(Error{}) +// SetError method registers the global or client common `Error` object into Resty. +// It is used for automatic unmarshalling if the response status code is greater than 399 and +// content type is JSON or XML. It can be a pointer or a non-pointer. +// +// client.SetError(&Error{}) +// // OR +// client.SetError(Error{}) func (c *Client) SetError(err interface{}) *Client { c.Error = typeOf(err) return c } -// SetRedirectPolicy method sets the client redirect poilicy. Resty provides ready to use -// redirect policies. Wanna create one for yourself refer to `redirect.go`. +// SetRedirectPolicy method sets the redirect policy for the client. Resty provides ready-to-use +// redirect policies. Wanna create one for yourself, refer to `redirect.go`. // -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) +// client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) // -// // Need multiple redirect policies together -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) +// // Need multiple redirect policies together +// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client { for _, p := range policies { if _, ok := p.(RedirectPolicy); !ok { @@ -582,7 +710,7 @@ func (c *Client) SetRetryCount(count int) *Client { return c } -// SetRetryWaitTime method sets default wait time to sleep before retrying +// SetRetryWaitTime method sets the default wait time for sleep before retrying // request. // // Default is 100 milliseconds. @@ -591,7 +719,7 @@ func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client { return c } -// SetRetryMaxWaitTime method sets max wait time to sleep before retrying +// SetRetryMaxWaitTime method sets the max wait time for sleep before retrying // request. // // Default is 2 seconds. @@ -600,28 +728,54 @@ func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client { return c } -// SetRetryAfter sets callback to calculate wait time between retries. +// SetRetryAfter sets a callback to calculate the wait time between retries. // Default (nil) implies exponential backoff with jitter func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client { c.RetryAfter = callback return c } -// AddRetryCondition method adds a retry condition function to array of functions +// SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. +// By default, Resty uses [encoding/json] package to marshal the request body. +func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { + c.JSONMarshal = marshaler + return c +} + +// SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body. +// By default, Resty uses [encoding/json] package to unmarshal the response body. +func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { + c.JSONUnmarshal = unmarshaler + return c +} + +// SetXMLMarshaler method sets the XML marshaler function to marshal the request body. +// By default, Resty uses [encoding/xml] package to marshal the request body. +func (c *Client) SetXMLMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { + c.XMLMarshal = marshaler + return c +} + +// SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. +// By default, Resty uses [encoding/xml] package to unmarshal the response body. +func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { + c.XMLUnmarshal = unmarshaler + return c +} + +// AddRetryCondition method adds a retry condition function to an array of functions // that are checked to determine if the request is retried. The request will -// retry if any of the functions return true and error is nil. +// retry if any functions return true and the error is nil. // -// Note: These retry conditions are applied on all Request made using this Client. -// For Request specific retry conditions check *Request.AddRetryCondition +// NOTE: These retry conditions are applied on all requests made using this Client. +// For [Request] specific retry conditions, check [Request.AddRetryCondition] func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client { c.RetryConditions = append(c.RetryConditions, condition) return c } // AddRetryAfterErrorCondition adds the basic condition of retrying after encountering -// an error from the http response -// -// Since v2.6.0 +// an error from the HTTP response func (c *Client) AddRetryAfterErrorCondition() *Client { c.AddRetryCondition(func(response *Response, err error) bool { return response.IsError() @@ -631,25 +785,31 @@ func (c *Client) AddRetryAfterErrorCondition() *Client { // AddRetryHook adds a side-effecting retry hook to an array of hooks // that will be executed on each retry. -// -// Since v2.6.0 func (c *Client) AddRetryHook(hook OnRetryFunc) *Client { c.RetryHooks = append(c.RetryHooks, hook) return c } -// SetTLSClientConfig method sets TLSClientConfig for underling client Transport. +// SetRetryResetReaders method enables the Resty client to seek the start of all +// file readers are given as multipart files if the object implements [io.ReadSeeker]. +func (c *Client) SetRetryResetReaders(b bool) *Client { + c.RetryResetReaders = b + return c +} + +// SetTLSClientConfig method sets TLSClientConfig for underlying client Transport. // // For Example: -// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial -// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) // -// // or One can disable security check (https) -// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) +// // One can set a custom root certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial +// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) +// +// // or One can disable security check (https) +// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) // -// Note: This method overwrites existing `TLSClientConfig`. +// NOTE: This method overwrites existing [http.Transport.TLSClientConfig] func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -658,14 +818,13 @@ func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { return c } -// SetProxy method sets the Proxy URL and Port for Resty client. -// client.SetProxy("http://proxyserver:8888") +// SetProxy method sets the Proxy URL and Port for the Resty client. // -// OR Without this `SetProxy` method, you could also set Proxy via environment variable. +// client.SetProxy("http://proxyserver:8888") // -// Refer to godoc `http.ProxyFromEnvironment`. +// OR you could also set Proxy via environment variable, refer to [http.ProxyFromEnvironment] func (c *Client) SetProxy(proxyURL string) *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -682,10 +841,11 @@ func (c *Client) SetProxy(proxyURL string) *Client { return c } -// RemoveProxy method removes the proxy configuration from Resty client -// client.RemoveProxy() +// RemoveProxy method removes the proxy configuration from the Resty client +// +// client.RemoveProxy() func (c *Client) RemoveProxy() *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -695,7 +855,7 @@ func (c *Client) RemoveProxy() *Client { return c } -// SetCertificates method helps to set client certificates into Resty conveniently. +// SetCertificates method helps to conveniently set client certificates into Resty. func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { config, err := c.tlsConfig() if err != nil { @@ -706,71 +866,104 @@ func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { return c } -// SetRootCertificate method helps to add one or more root certificates into Resty client -// client.SetRootCertificate("/path/to/root/pemFile.pem") +// SetRootCertificate method helps to add one or more root certificates into the Resty client +// +// client.SetRootCertificate("/path/to/root/pemFile.pem") func (c *Client) SetRootCertificate(pemFilePath string) *Client { - rootPemData, err := ioutil.ReadFile(pemFilePath) + rootPemData, err := os.ReadFile(pemFilePath) if err != nil { c.log.Errorf("%v", err) return c } + c.handleCAs("root", rootPemData) + return c +} - config, err := c.tlsConfig() +// SetRootCertificateFromString method helps to add one or more root certificates +// into the Resty client +// +// client.SetRootCertificateFromString("pem certs content") +func (c *Client) SetRootCertificateFromString(pemCerts string) *Client { + c.handleCAs("root", []byte(pemCerts)) + return c +} + +// SetClientRootCertificate method helps to add one or more client's root +// certificates into the Resty client +// +// client.SetClientRootCertificate("/path/to/root/pemFile.pem") +func (c *Client) SetClientRootCertificate(pemFilePath string) *Client { + rootPemData, err := os.ReadFile(pemFilePath) if err != nil { c.log.Errorf("%v", err) return c } - if config.RootCAs == nil { - config.RootCAs = x509.NewCertPool() - } + c.handleCAs("client", rootPemData) + return c +} - config.RootCAs.AppendCertsFromPEM(rootPemData) +// SetClientRootCertificateFromString method helps to add one or more clients +// root certificates into the Resty client +// +// client.SetClientRootCertificateFromString("pem certs content") +func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client { + c.handleCAs("client", []byte(pemCerts)) return c } -// SetRootCertificateFromString method helps to add one or more root certificates into Resty client -// client.SetRootCertificateFromString("pem file content") -func (c *Client) SetRootCertificateFromString(pemContent string) *Client { +func (c *Client) handleCAs(scope string, permCerts []byte) { config, err := c.tlsConfig() if err != nil { c.log.Errorf("%v", err) - return c - } - if config.RootCAs == nil { - config.RootCAs = x509.NewCertPool() + return } - config.RootCAs.AppendCertsFromPEM([]byte(pemContent)) - return c + switch scope { + case "root": + if config.RootCAs == nil { + config.RootCAs = x509.NewCertPool() + } + config.RootCAs.AppendCertsFromPEM(permCerts) + case "client": + if config.ClientCAs == nil { + config.ClientCAs = x509.NewCertPool() + } + config.ClientCAs.AppendCertsFromPEM(permCerts) + } } -// SetOutputDirectory method sets output directory for saving HTTP response into file. -// If the output directory not exists then resty creates one. This setting is optional one, -// if you're planning using absolute path in `Request.SetOutput` and can used together. -// client.SetOutputDirectory("/save/http/response/here") +// SetOutputDirectory method sets the output directory for saving HTTP responses in a file. +// Resty creates one if the output directory does not exist. This setting is optional, +// if you plan to use the absolute path in [Request.SetOutput] and can used together. +// +// client.SetOutputDirectory("/save/http/response/here") func (c *Client) SetOutputDirectory(dirPath string) *Client { c.outputDirectory = dirPath return c } -// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` -// compatible interface implementation in the resty client. -// -// Note: -// -// - If transport is not type of `*http.Transport` then you may not be able to -// take advantage of some of the Resty client settings. -// -// - It overwrites the Resty client transport instance and it's configurations. +// SetRateLimiter sets an optional [RateLimiter]. If set, the rate limiter will control +// all requests were made by this client. +func (c *Client) SetRateLimiter(rl RateLimiter) *Client { + c.rateLimiter = rl + return c +} + +// SetTransport method sets custom [http.Transport] or any [http.RoundTripper] +// compatible interface implementation in the Resty client. // -// transport := &http.Transport{ -// // somthing like Proxying to httptest.Server, etc... -// Proxy: func(req *http.Request) (*url.URL, error) { -// return url.Parse(server.URL) -// }, -// } +// transport := &http.Transport{ +// // something like Proxying to httptest.Server, etc... +// Proxy: func(req *http.Request) (*url.URL, error) { +// return url.Parse(server.URL) +// }, +// } +// client.SetTransport(transport) // -// client.SetTransport(transport) +// NOTE: +// - If transport is not the type of `*http.Transport`, then you may not be able to +// take advantage of some of the Resty client settings. +// - It overwrites the Resty client transport instance and its configurations. func (c *Client) SetTransport(transport http.RoundTripper) *Client { if transport != nil { c.httpClient.Transport = transport @@ -778,8 +971,9 @@ func (c *Client) SetTransport(transport http.RoundTripper) *Client { return c } -// SetScheme method sets custom scheme in the Resty client. It's way to override default. -// client.SetScheme("http") +// SetScheme method sets a custom scheme for the Resty client. It's a way to override the default. +// +// client.SetScheme("http") func (c *Client) SetScheme(scheme string) *Client { if !IsStringEmpty(scheme) { c.scheme = strings.TrimSpace(scheme) @@ -787,35 +981,39 @@ func (c *Client) SetScheme(scheme string) *Client { return c } -// SetCloseConnection method sets variable `Close` in http request struct with the given +// SetCloseConnection method sets variable `Close` in HTTP request struct with the given // value. More info: https://golang.org/src/net/http/request.go func (c *Client) SetCloseConnection(close bool) *Client { c.closeConnection = close return c } -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. +// SetDoNotParseResponse method instructs Resty not to parse the response body automatically. +// Resty exposes the raw response body as [io.ReadCloser]. If you use it, do not +// forget to close the body, otherwise, you might get into connection leaks, and connection +// reuse may not happen. // -// Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. -func (c *Client) SetDoNotParseResponse(parse bool) *Client { - c.notParseResponse = parse +// NOTE: [Response] middlewares are not executed using this option. You have +// taken over the control of response parsing from Resty. +func (c *Client) SetDoNotParseResponse(notParse bool) *Client { + c.notParseResponse = notParse return c } -// SetPathParam method sets single URL path key-value pair in the +// SetPathParam method sets a single URL path key-value pair in the // Resty client instance. -// client.SetPathParam("userId", "sample@sample.com") // -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details +// client.SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// // It replaces the value of the key while composing the request URL. +// The value will be escaped using [url.PathEscape] function. // -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. +// It can be overridden at the request level, +// see [Request.SetPathParam] or [Request.SetPathParams] func (c *Client) SetPathParam(param, value string) *Client { c.PathParams[param] = value return c @@ -823,18 +1021,22 @@ func (c *Client) SetPathParam(param, value string) *Client { // SetPathParams method sets multiple URL path key-value pairs at one go in the // Resty client instance. -// client.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details +// +// client.SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details +// // It replaces the value of the key while composing the request URL. +// The values will be escaped using [url.PathEscape] function. // -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. +// It can be overridden at the request level, +// see [Request.SetPathParam] or [Request.SetPathParams] func (c *Client) SetPathParams(params map[string]string) *Client { for p, v := range params { c.SetPathParam(p, v) @@ -842,57 +1044,158 @@ func (c *Client) SetPathParams(params map[string]string) *Client { return c } -// SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. +// SetRawPathParam method sets a single URL path key-value pair in the +// Resty client instance. +// +// client.SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing the request URL. +// The value will be used as it is and will not be escaped. +// +// It can be overridden at the request level, +// see [Request.SetRawPathParam] or [Request.SetRawPathParams] +func (c *Client) SetRawPathParam(param, value string) *Client { + c.RawPathParams[param] = value + return c +} + +// SetRawPathParams method sets multiple URL path key-value pairs at one go in the +// Resty client instance. +// +// client.SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details +// +// It replaces the value of the key while composing the request URL. +// The values will be used as they are and will not be escaped. +// +// It can be overridden at the request level, +// see [Request.SetRawPathParam] or [Request.SetRawPathParams] +func (c *Client) SetRawPathParams(params map[string]string) *Client { + for p, v := range params { + c.SetRawPathParam(p, v) + } + return c +} + +// SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. +// By default, escape HTML is false. // -// Note: This option only applicable to standard JSON Marshaller. +// NOTE: This option only applies to the standard JSON Marshaller used by Resty. +// +// It can be overridden at the request level, see [Client.SetJSONEscapeHTML] func (c *Client) SetJSONEscapeHTML(b bool) *Client { c.jsonEscapeHTML = b return c } -// EnableTrace method enables the Resty client trace for the requests fired from -// the client using `httptrace.ClientTrace` and provides insights. +// SetResponseBodyLimit method sets a maximum body size limit in bytes on response, +// avoid reading too much data to memory. // -// client := resty.New().EnableTrace() +// Client will return [resty.ErrResponseBodyTooLarge] if the body size of the body +// in the uncompressed response is larger than the limit. +// Body size limit will not be enforced in the following cases: +// - ResponseBodyLimit <= 0, which is the default behavior. +// - [Request.SetOutput] is called to save response data to the file. +// - "DoNotParseResponse" is set for client or request. // -// resp, err := client.R().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) +// It can be overridden at the request level; see [Request.SetResponseBodyLimit] +func (c *Client) SetResponseBodyLimit(v int) *Client { + c.ResponseBodyLimit = v + return c +} + +// EnableTrace method enables the Resty client trace for the requests fired from +// the client using [httptrace.ClientTrace] and provides insights. // -// Also `Request.EnableTrace` available too to get trace info for single request. +// client := resty.New().EnableTrace() // -// Since v2.0.0 +// resp, err := client.R().Get("https://httpbin.org/get") +// fmt.Println("Error:", err) +// fmt.Println("Trace Info:", resp.Request.TraceInfo()) +// +// The method [Request.EnableTrace] is also available to get trace info for a single request. func (c *Client) EnableTrace() *Client { c.trace = true return c } -// DisableTrace method disables the Resty client trace. Refer to `Client.EnableTrace`. -// -// Since v2.0.0 +// DisableTrace method disables the Resty client trace. Refer to [Client.EnableTrace]. func (c *Client) DisableTrace() *Client { c.trace = false return c } -// IsProxySet method returns the true is proxy is set from resty client otherwise -// false. By default proxy is set from environment, refer to `http.ProxyFromEnvironment`. +// EnableGenerateCurlOnDebug method enables the generation of CURL commands in the debug log. +// It works in conjunction with debug mode. +// +// NOTE: Use with care. +// - Potential to leak sensitive data from [Request] and [Response] in the debug log. +// - Beware of memory usage since the request body is reread. +func (c *Client) EnableGenerateCurlOnDebug() *Client { + c.generateCurlOnDebug = true + return c +} + +// DisableGenerateCurlOnDebug method disables the option set by [Client.EnableGenerateCurlOnDebug]. +func (c *Client) DisableGenerateCurlOnDebug() *Client { + c.generateCurlOnDebug = false + return c +} + +// IsProxySet method returns the true is proxy is set from the Resty client; otherwise +// false. By default, the proxy is set from the environment variable; refer to [http.ProxyFromEnvironment]. func (c *Client) IsProxySet() bool { return c.proxyURL != nil } -// GetClient method returns the current `http.Client` used by the resty client. +// GetClient method returns the underlying [http.Client] used by the Resty. func (c *Client) GetClient() *http.Client { return c.httpClient } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client Unexported methods -//_______________________________________________________________________ +// Clone returns a clone of the original client. +// +// NOTE: Use with care: +// - Interface values are not deeply cloned. Thus, both the original and the +// clone will use the same value. +// - This function is not safe for concurrent use. You should only use this method +// when you are sure that any other goroutine is not using the client. +func (c *Client) Clone() *Client { + // dereference the pointer and copy the value + cc := *c + + // lock values should not be copied - thus new values are used. + cc.afterResponseLock = &sync.RWMutex{} + cc.udBeforeRequestLock = &sync.RWMutex{} + return &cc +} + +func (c *Client) executeBefore(req *Request) error { + // Lock the user-defined pre-request hooks. + c.udBeforeRequestLock.RLock() + defer c.udBeforeRequestLock.RUnlock() + + // Lock the post-request hooks. + c.afterResponseLock.RLock() + defer c.afterResponseLock.RUnlock() -// Executes method executes the given `Request` object and returns response -// error. -func (c *Client) execute(req *Request) (*Response, error) { // Apply Request middleware var err error @@ -900,14 +1203,22 @@ func (c *Client) execute(req *Request) (*Response, error) { // to modify the *resty.Request object for _, f := range c.udBeforeRequest { if err = f(c, req); err != nil { - return nil, wrapNoRetryErr(err) + return wrapNoRetryErr(err) + } + } + + // If there is a rate limiter set for this client, the Execute call + // will return an error if the rate limit is exceeded. + if req.client.rateLimiter != nil { + if !req.client.rateLimiter.Allow() { + return wrapNoRetryErr(ErrRateLimitExceeded) } } // resty middlewares for _, f := range c.beforeRequest { if err = f(c, req); err != nil { - return nil, wrapNoRetryErr(err) + return wrapNoRetryErr(err) } } @@ -918,15 +1229,23 @@ func (c *Client) execute(req *Request) (*Response, error) { // call pre-request if defined if c.preReqHook != nil { if err = c.preReqHook(c, req.RawRequest); err != nil { - return nil, wrapNoRetryErr(err) + return wrapNoRetryErr(err) } } if err = requestLogger(c, req); err != nil { - return nil, wrapNoRetryErr(err) + return wrapNoRetryErr(err) } - req.RawRequest.Body = newRequestBodyReleaser(req.RawRequest.Body, req.bodyBuf) + return nil +} + +// Executes method executes the given `Request` object and returns +// response or error. +func (c *Client) execute(req *Request) (*Response, error) { + if err := c.executeBefore(req); err != nil { + return nil, err + } req.Time = time.Now() resp, err := c.httpClient.Do(req.RawRequest) @@ -938,7 +1257,13 @@ func (c *Client) execute(req *Request) (*Response, error) { if err != nil || req.notParseResponse || c.notParseResponse { response.setReceivedAt() - return response, err + if logErr := responseLogger(c, response); logErr != nil { + return response, wrapErrors(logErr, err) + } + if err != nil { + return response, err + } + return response, nil } if !req.isSaveResponse { @@ -950,6 +1275,7 @@ func (c *Client) execute(req *Request) (*Response, error) { if _, ok := body.(*gzip.Reader); !ok { body, err = gzip.NewReader(body) if err != nil { + err = wrapErrors(responseLogger(c, response), err) response.setReceivedAt() return response, err } @@ -957,7 +1283,8 @@ func (c *Client) execute(req *Request) (*Response, error) { } } - if response.body, err = ioutil.ReadAll(body); err != nil { + if response.body, err = readAllWithLimit(body, req.responseBodyLimit); err != nil { + err = wrapErrors(responseLogger(c, response), err) response.setReceivedAt() return response, err } @@ -968,6 +1295,11 @@ func (c *Client) execute(req *Request) (*Response, error) { response.setReceivedAt() // after we read the body // Apply Response middleware + err = responseLogger(c, response) + if err != nil { + return response, wrapNoRetryErr(err) + } + for _, f := range c.afterResponse { if err = f(c, response); err != nil { break @@ -977,9 +1309,42 @@ func (c *Client) execute(req *Request) (*Response, error) { return response, wrapNoRetryErr(err) } +var ErrResponseBodyTooLarge = errors.New("resty: response body too large") + +// https://github.com/golang/go/issues/51115 +// [io.LimitedReader] can only return [io.EOF] +func readAllWithLimit(r io.Reader, maxSize int) ([]byte, error) { + if maxSize <= 0 { + return io.ReadAll(r) + } + + var buf [512]byte // make buf stack allocated + result := make([]byte, 0, 512) + total := 0 + for { + n, err := r.Read(buf[:]) + total += n + if total > maxSize { + return nil, ErrResponseBodyTooLarge + } + + if err != nil { + if err == io.EOF { + result = append(result, buf[:n]...) + break + } + return nil, err + } + + result = append(result, buf[:n]...) + } + + return result, nil +} + // getting TLS client config if not exists then create one func (c *Client) tlsConfig() (*tls.Config, error) { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { return nil, err } @@ -989,9 +1354,11 @@ func (c *Client) tlsConfig() (*tls.Config, error) { return transport.TLSClientConfig, nil } -// Transport method returns `*http.Transport` currently in use or error -// in case currently used `transport` is not a `*http.Transport`. -func (c *Client) transport() (*http.Transport, error) { +// Transport method returns [http.Transport] currently in use or error +// in case the currently used `transport` is not a [http.Transport]. +// +// Since v2.8.0 has become exported method. +func (c *Client) Transport() (*http.Transport, error) { if transport, ok := c.httpClient.Transport.(*http.Transport); ok { return transport, nil } @@ -1004,7 +1371,7 @@ func (c *Client) outputLogTo(w io.Writer) *Client { return c } -// ResponseError is a wrapper for including the server response with an error. +// ResponseError is a wrapper that includes the server response with an error. // Neither the err nor the response should be nil. type ResponseError struct { Response *Response @@ -1019,8 +1386,8 @@ func (e *ResponseError) Unwrap() error { return e.Err } -// Helper to run onErrorHooks hooks. -// It wraps the error in a ResponseError if the resp is not nil +// Helper to run errorHooks hooks. +// It wraps the error in a [ResponseError] if the resp is not nil // so hooks can access it. func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { if err != nil { @@ -1030,6 +1397,24 @@ func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { for _, h := range c.errorHooks { h(req, err) } + } else { + for _, h := range c.successHooks { + h(c, resp) + } + } +} + +// Helper to run panicHooks hooks. +func (c *Client) onPanicHooks(req *Request, err error) { + for _, h := range c.panicHooks { + h(req, err) + } +} + +// Helper to run invalidHooks hooks. +func (c *Client) onInvalidHooks(req *Request, err error) { + for _, h := range c.invalidHooks { + h(req, err) } } @@ -1037,14 +1422,14 @@ func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { // File struct and its methods //_______________________________________________________________________ -// File struct represent file information for multipart request +// File struct represents file information for multipart request type File struct { Name string ParamName string io.Reader } -// String returns string value of current file details +// String method returns the string value of current file details func (f *File) String() string { return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name) } @@ -1053,7 +1438,7 @@ func (f *File) String() string { // MultipartField struct //_______________________________________________________________________ -// MultipartField struct represent custom data part for multipart request +// MultipartField struct represents the custom data part for a multipart request type MultipartField struct { Param string FileName string @@ -1061,10 +1446,6 @@ type MultipartField struct { io.Reader } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Unexported package methods -//_______________________________________________________________________ - func createClient(hc *http.Client) *Client { if hc.Transport == nil { hc.Transport = createTransport(nil) @@ -1078,15 +1459,19 @@ func createClient(hc *http.Client) *Client { RetryWaitTime: defaultWaitTime, RetryMaxWaitTime: defaultMaxWaitTime, PathParams: make(map[string]string), + RawPathParams: make(map[string]string), JSONMarshal: json.Marshal, JSONUnmarshal: json.Unmarshal, XMLMarshal: xml.Marshal, XMLUnmarshal: xml.Unmarshal, HeaderAuthorizationKey: http.CanonicalHeaderKey("Authorization"), + AuthScheme: "Bearer", - jsonEscapeHTML: true, - httpClient: hc, - debugBodySizeLimit: math.MaxInt32, + jsonEscapeHTML: true, + httpClient: hc, + debugBodySizeLimit: math.MaxInt32, + udBeforeRequestLock: &sync.RWMutex{}, + afterResponseLock: &sync.RWMutex{}, } // Logger @@ -1099,6 +1484,7 @@ func createClient(hc *http.Client) *Client { parseRequestBody, createHTTPRequest, addCredentials, + createCurlCmd, } // user defined request middlewares @@ -1106,7 +1492,6 @@ func createClient(hc *http.Client) *Client { // default after response middlewares c.afterResponse = []ResponseMiddleware{ - responseLogger, parseResponseBody, saveResponseIntoFile, } diff --git a/vendor/github.com/go-resty/resty/v2/digest.go b/vendor/github.com/go-resty/resty/v2/digest.go new file mode 100644 index 0000000000..3a08477de2 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/digest.go @@ -0,0 +1,327 @@ +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com) +// 2023 Segev Dagan (https://github.com/segevda) +// 2024 Philipp Wolfer (https://github.com/phw) +// All rights reserved. +// resty source code and usage is governed by a MIT style +// license that can be found in the LICENSE file. + +package resty + +import ( + "crypto/md5" + "crypto/rand" + "crypto/sha256" + "crypto/sha512" + "errors" + "fmt" + "hash" + "io" + "net/http" + "strings" +) + +var ( + ErrDigestBadChallenge = errors.New("digest: challenge is bad") + ErrDigestCharset = errors.New("digest: unsupported charset") + ErrDigestAlgNotSupported = errors.New("digest: algorithm is not supported") + ErrDigestQopNotSupported = errors.New("digest: no supported qop in list") + ErrDigestNoQop = errors.New("digest: qop must be specified") +) + +var hashFuncs = map[string]func() hash.Hash{ + "": md5.New, + "MD5": md5.New, + "MD5-sess": md5.New, + "SHA-256": sha256.New, + "SHA-256-sess": sha256.New, + "SHA-512-256": sha512.New, + "SHA-512-256-sess": sha512.New, +} + +type digestCredentials struct { + username, password string +} + +type digestTransport struct { + digestCredentials + transport http.RoundTripper +} + +func (dt *digestTransport) RoundTrip(req *http.Request) (*http.Response, error) { + // Copy the request, so we don't modify the input. + req2 := new(http.Request) + *req2 = *req + req2.Header = make(http.Header) + for k, s := range req.Header { + req2.Header[k] = s + } + + // Fix http: ContentLength=xxx with Body length 0 + if req2.Body == nil { + req2.ContentLength = 0 + } else if req2.GetBody != nil { + var err error + req2.Body, err = req2.GetBody() + if err != nil { + return nil, err + } + } + + // Make a request to get the 401 that contains the challenge. + resp, err := dt.transport.RoundTrip(req) + if err != nil || resp.StatusCode != http.StatusUnauthorized { + return resp, err + } + chal := resp.Header.Get(hdrWwwAuthenticateKey) + if chal == "" { + return resp, ErrDigestBadChallenge + } + + c, err := parseChallenge(chal) + if err != nil { + return resp, err + } + + // Form credentials based on the challenge + cr := dt.newCredentials(req2, c) + auth, err := cr.authorize() + if err != nil { + return resp, err + } + err = resp.Body.Close() + if err != nil { + return nil, err + } + + // Make authenticated request + req2.Header.Set(hdrAuthorizationKey, auth) + return dt.transport.RoundTrip(req2) +} + +func (dt *digestTransport) newCredentials(req *http.Request, c *challenge) *credentials { + return &credentials{ + username: dt.username, + userhash: c.userhash, + realm: c.realm, + nonce: c.nonce, + digestURI: req.URL.RequestURI(), + algorithm: c.algorithm, + sessionAlg: strings.HasSuffix(c.algorithm, "-sess"), + opaque: c.opaque, + messageQop: c.qop, + nc: 0, + method: req.Method, + password: dt.password, + } +} + +type challenge struct { + realm string + domain string + nonce string + opaque string + stale string + algorithm string + qop string + userhash string +} + +func (c *challenge) setValue(k, v string) error { + switch k { + case "realm": + c.realm = v + case "domain": + c.domain = v + case "nonce": + c.nonce = v + case "opaque": + c.opaque = v + case "stale": + c.stale = v + case "algorithm": + c.algorithm = v + case "qop": + c.qop = v + case "charset": + if strings.ToUpper(v) != "UTF-8" { + return ErrDigestCharset + } + case "userhash": + c.userhash = v + default: + return ErrDigestBadChallenge + } + return nil +} + +func parseChallenge(input string) (*challenge, error) { + const ws = " \n\r\t" + s := strings.Trim(input, ws) + if !strings.HasPrefix(s, "Digest ") { + return nil, ErrDigestBadChallenge + } + s = strings.Trim(s[7:], ws) + c := &challenge{} + b := strings.Builder{} + key := "" + quoted := false + for _, r := range s { + switch r { + case '"': + quoted = !quoted + case ',': + if quoted { + b.WriteRune(r) + } else { + val := strings.Trim(b.String(), ws) + b.Reset() + if err := c.setValue(key, val); err != nil { + return nil, err + } + key = "" + } + case '=': + if quoted { + b.WriteRune(r) + } else { + key = strings.Trim(b.String(), ws) + b.Reset() + } + default: + b.WriteRune(r) + } + } + if quoted || (key == "" && b.Len() > 0) { + return nil, ErrDigestBadChallenge + } + if key != "" { + val := strings.Trim(b.String(), ws) + if err := c.setValue(key, val); err != nil { + return nil, err + } + } + return c, nil +} + +type credentials struct { + username string + userhash string + realm string + nonce string + digestURI string + algorithm string + sessionAlg bool + cNonce string + opaque string + messageQop string + nc int + method string + password string +} + +func (c *credentials) authorize() (string, error) { + if _, ok := hashFuncs[c.algorithm]; !ok { + return "", ErrDigestAlgNotSupported + } + + if err := c.validateQop(); err != nil { + return "", err + } + + resp, err := c.resp() + if err != nil { + return "", err + } + + sl := make([]string, 0, 10) + if c.userhash == "true" { + // RFC 7616 3.4.4 + c.username = c.h(fmt.Sprintf("%s:%s", c.username, c.realm)) + sl = append(sl, fmt.Sprintf(`userhash=%s`, c.userhash)) + } + sl = append(sl, fmt.Sprintf(`username="%s"`, c.username)) + sl = append(sl, fmt.Sprintf(`realm="%s"`, c.realm)) + sl = append(sl, fmt.Sprintf(`nonce="%s"`, c.nonce)) + sl = append(sl, fmt.Sprintf(`uri="%s"`, c.digestURI)) + sl = append(sl, fmt.Sprintf(`response="%s"`, resp)) + sl = append(sl, fmt.Sprintf(`algorithm=%s`, c.algorithm)) + if c.opaque != "" { + sl = append(sl, fmt.Sprintf(`opaque="%s"`, c.opaque)) + } + if c.messageQop != "" { + sl = append(sl, fmt.Sprintf("qop=%s", c.messageQop)) + sl = append(sl, fmt.Sprintf("nc=%08x", c.nc)) + sl = append(sl, fmt.Sprintf(`cnonce="%s"`, c.cNonce)) + } + + return fmt.Sprintf("Digest %s", strings.Join(sl, ", ")), nil +} + +func (c *credentials) validateQop() error { + // Currently only supporting auth quality of protection. TODO: add auth-int support + // NOTE: cURL support auth-int qop for requests other than POST and PUT (i.e. w/o body) by hashing an empty string + // is this applicable for resty? see: https://github.com/curl/curl/blob/307b7543ea1e73ab04e062bdbe4b5bb409eaba3a/lib/vauth/digest.c#L774 + if c.messageQop == "" { + return ErrDigestNoQop + } + possibleQops := strings.Split(c.messageQop, ",") + var authSupport bool + for _, qop := range possibleQops { + qop = strings.TrimSpace(qop) + if qop == "auth" { + authSupport = true + break + } + } + if !authSupport { + return ErrDigestQopNotSupported + } + + c.messageQop = "auth" + + return nil +} + +func (c *credentials) h(data string) string { + hfCtor := hashFuncs[c.algorithm] + hf := hfCtor() + _, _ = hf.Write([]byte(data)) // Hash.Write never returns an error + return fmt.Sprintf("%x", hf.Sum(nil)) +} + +func (c *credentials) resp() (string, error) { + c.nc++ + + b := make([]byte, 16) + _, err := io.ReadFull(rand.Reader, b) + if err != nil { + return "", err + } + c.cNonce = fmt.Sprintf("%x", b)[:32] + + ha1 := c.ha1() + ha2 := c.ha2() + + return c.kd(ha1, fmt.Sprintf("%s:%08x:%s:%s:%s", + c.nonce, c.nc, c.cNonce, c.messageQop, ha2)), nil +} + +func (c *credentials) kd(secret, data string) string { + return c.h(fmt.Sprintf("%s:%s", secret, data)) +} + +// RFC 7616 3.4.2 +func (c *credentials) ha1() string { + ret := c.h(fmt.Sprintf("%s:%s:%s", c.username, c.realm, c.password)) + if c.sessionAlg { + return c.h(fmt.Sprintf("%s:%s:%s", ret, c.nonce, c.cNonce)) + } + + return ret +} + +// RFC 7616 3.4.3 +func (c *credentials) ha2() string { + // currently no auth-int support + return c.h(fmt.Sprintf("%s:%s", c.method, c.digestURI)) +} diff --git a/vendor/github.com/go-resty/resty/v2/middleware.go b/vendor/github.com/go-resty/resty/v2/middleware.go index 0e8ac2b698..daf63addf2 100644 --- a/vendor/github.com/go-resty/resty/v2/middleware.go +++ b/vendor/github.com/go-resty/resty/v2/middleware.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -9,13 +9,13 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" + "strconv" "strings" "time" ) @@ -27,15 +27,76 @@ const debugRequestLogKey = "__restyDebugRequestLog" //_______________________________________________________________________ func parseRequestURL(c *Client, r *Request) error { - // GitHub #103 Path Params - if len(r.PathParams) > 0 { + if l := len(c.PathParams) + len(c.RawPathParams) + len(r.PathParams) + len(r.RawPathParams); l > 0 { + params := make(map[string]string, l) + + // GitHub #103 Path Params for p, v := range r.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) + params[p] = url.PathEscape(v) } - } - if len(c.PathParams) > 0 { for p, v := range c.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) + if _, ok := params[p]; !ok { + params[p] = url.PathEscape(v) + } + } + + // GitHub #663 Raw Path Params + for p, v := range r.RawPathParams { + if _, ok := params[p]; !ok { + params[p] = v + } + } + for p, v := range c.RawPathParams { + if _, ok := params[p]; !ok { + params[p] = v + } + } + + if len(params) > 0 { + var prev int + buf := acquireBuffer() + defer releaseBuffer(buf) + // search for the next or first opened curly bracket + for curr := strings.Index(r.URL, "{"); curr == 0 || curr >= prev; curr = prev + strings.Index(r.URL[prev:], "{") { + // write everything from the previous position up to the current + if curr > prev { + buf.WriteString(r.URL[prev:curr]) + } + // search for the closed curly bracket from current position + next := curr + strings.Index(r.URL[curr:], "}") + // if not found, then write the remainder and exit + if next < curr { + buf.WriteString(r.URL[curr:]) + prev = len(r.URL) + break + } + // special case for {}, without parameter's name + if next == curr+1 { + buf.WriteString("{}") + } else { + // check for the replacement + key := r.URL[curr+1 : next] + value, ok := params[key] + /// keep the original string if the replacement not found + if !ok { + value = r.URL[curr : next+1] + } + buf.WriteString(value) + } + + // set the previous position after the closed curly bracket + prev = next + 1 + if prev >= len(r.URL) { + break + } + } + if buf.Len() > 0 { + // write remainder + if prev < len(r.URL) { + buf.WriteString(r.URL[prev:]) + } + r.URL = buf.String() + } } } @@ -53,7 +114,12 @@ func parseRequestURL(c *Client, r *Request) error { r.URL = "/" + r.URL } - reqURL, err = url.Parse(c.HostURL + r.URL) + // TODO: change to use c.BaseURL only in v3.0.0 + baseURL := c.BaseURL + if len(baseURL) == 0 { + baseURL = c.HostURL + } + reqURL, err = url.Parse(baseURL + r.URL) if err != nil { return err } @@ -65,33 +131,36 @@ func parseRequestURL(c *Client, r *Request) error { } // Adding Query Param - query := make(url.Values) - for k, v := range c.QueryParam { - for _, iv := range v { - query.Add(k, iv) - } - } + if len(c.QueryParam)+len(r.QueryParam) > 0 { + for k, v := range c.QueryParam { + // skip query parameter if it was set in request + if _, ok := r.QueryParam[k]; ok { + continue + } - for k, v := range r.QueryParam { - // remove query param from client level by key - // since overrides happens for that key in the request - query.Del(k) + r.QueryParam[k] = v[:] + } - for _, iv := range v { - query.Add(k, iv) + // GitHub #123 Preserve query string order partially. + // Since not feasible in `SetQuery*` resty methods, because + // standard package `url.Encode(...)` sorts the query params + // alphabetically + if len(r.QueryParam) > 0 { + if IsStringEmpty(reqURL.RawQuery) { + reqURL.RawQuery = r.QueryParam.Encode() + } else { + reqURL.RawQuery = reqURL.RawQuery + "&" + r.QueryParam.Encode() + } } } - // GitHub #123 Preserve query string order partially. - // Since not feasible in `SetQuery*` resty methods, because - // standard package `url.Encode(...)` sorts the query params - // alphabetically - if len(query) > 0 { - if IsStringEmpty(reqURL.RawQuery) { - reqURL.RawQuery = query.Encode() - } else { - reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode() - } + // GH#797 Unescape query parameters + if r.unescapeQueryParams && len(reqURL.RawQuery) > 0 { + // at this point, all errors caught up in the above operations + // so ignore the return error on query unescape; I realized + // while writing the unit test + unescapedQuery, _ := url.QueryUnescape(reqURL.RawQuery) + reqURL.RawQuery = strings.ReplaceAll(unescapedQuery, " ", "+") // otherwise request becomes bad request } r.URL = reqURL.String() @@ -100,71 +169,61 @@ func parseRequestURL(c *Client, r *Request) error { } func parseRequestHeader(c *Client, r *Request) error { - hdr := make(http.Header) - for k := range c.Header { - hdr[k] = append(hdr[k], c.Header[k]...) - } - - for k := range r.Header { - hdr.Del(k) - hdr[k] = append(hdr[k], r.Header[k]...) + for k, v := range c.Header { + if _, ok := r.Header[k]; ok { + continue + } + r.Header[k] = v[:] } - if IsStringEmpty(hdr.Get(hdrUserAgentKey)) { - hdr.Set(hdrUserAgentKey, hdrUserAgentValue) + if IsStringEmpty(r.Header.Get(hdrUserAgentKey)) { + r.Header.Set(hdrUserAgentKey, hdrUserAgentValue) } - ct := hdr.Get(hdrContentTypeKey) - if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && - (IsJSONType(ct) || IsXMLType(ct)) { - hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey)) + if ct := r.Header.Get(hdrContentTypeKey); IsStringEmpty(r.Header.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && (IsJSONType(ct) || IsXMLType(ct)) { + r.Header.Set(hdrAcceptKey, r.Header.Get(hdrContentTypeKey)) } - r.Header = hdr - return nil } -func parseRequestBody(c *Client, r *Request) (err error) { +func parseRequestBody(c *Client, r *Request) error { if isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - // Handling Multipart - if r.isMultiPart && !(r.Method == MethodPatch) { - if err = handleMultipart(c, r); err != nil { - return + switch { + case r.isMultiPart: // Handling Multipart + if err := handleMultipart(c, r); err != nil { + return err } - - goto CL - } - - // Handling Form Data - if len(c.FormData) > 0 || len(r.FormData) > 0 { + case len(c.FormData) > 0 || len(r.FormData) > 0: // Handling Form Data handleFormData(c, r) - - goto CL - } - - // Handling Request body - if r.Body != nil { + case r.Body == nil && r.bodyBuf == nil: // Handling Request body when nil body + // Go http library omits Content-Length if body is nil; use http.NoBody to force it if SetContentLength is true + r.Body = http.NoBody + fallthrough + case r.Body != nil: // Handling Request body handleContentType(c, r) - if err = handleRequestBody(c, r); err != nil { - return + if err := handleRequestBody(c, r); err != nil { + return err } } } -CL: // by default resty won't set content length, you can if you want to :) - if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil { - r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len())) + if c.setContentLength || r.setContentLength { + if r.bodyBuf == nil { + r.Header.Set(hdrContentLengthKey, "0") + } else { + r.Header.Set(hdrContentLengthKey, strconv.Itoa(r.bodyBuf.Len())) + } } - return + return nil } func createHTTPRequest(c *Client, r *Request) (err error) { if r.bodyBuf == nil { - if reader, ok := r.Body.(io.Reader); ok { + if reader, ok := r.Body.(io.Reader); ok && isPayloadSupported(r.Method, c.AllowGetMethodPayload) { r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader) } else if c.setContentLength || r.setContentLength { r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody) @@ -172,7 +231,9 @@ func createHTTPRequest(c *Client, r *Request) (err error) { r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil) } } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) + // fix data race: must deep copy. + bodyBuf := bytes.NewBuffer(append([]byte{}, r.bodyBuf.Bytes()...)) + r.RawRequest, err = http.NewRequest(r.Method, r.URL, bodyBuf) } if err != nil { @@ -206,17 +267,19 @@ func createHTTPRequest(c *Client, r *Request) (err error) { r.RawRequest = r.RawRequest.WithContext(r.ctx) } - bodyCopy, err := getBodyCopy(r) - if err != nil { - return err - } - // assign get body func for the underlying raw request instance - r.RawRequest.GetBody = func() (io.ReadCloser, error) { + if r.RawRequest.GetBody == nil { + bodyCopy, err := getBodyCopy(r) + if err != nil { + return err + } if bodyCopy != nil { - return ioutil.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil + buf := bodyCopy.Bytes() + r.RawRequest.GetBody = func() (io.ReadCloser, error) { + b := bytes.NewReader(buf) + return io.NopCloser(b), nil + } } - return nil, nil } return @@ -235,43 +298,60 @@ func addCredentials(c *Client, r *Request) error { if !c.DisableWarn { if isBasicAuth && !strings.HasPrefix(r.URL, "https") { - c.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS") + r.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS") } } - // Set the Authorization Header Scheme - var authScheme string - if !IsStringEmpty(r.AuthScheme) { - authScheme = r.AuthScheme - } else if !IsStringEmpty(c.AuthScheme) { - authScheme = c.AuthScheme - } else { - authScheme = "Bearer" + // Build the token Auth header + if !IsStringEmpty(r.Token) { + r.RawRequest.Header.Set(c.HeaderAuthorizationKey, strings.TrimSpace(r.AuthScheme+" "+r.Token)) + } else if !IsStringEmpty(c.Token) { + r.RawRequest.Header.Set(c.HeaderAuthorizationKey, strings.TrimSpace(r.AuthScheme+" "+c.Token)) } - // Build the Token Auth header - if !IsStringEmpty(r.Token) { // takes precedence - r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+r.Token) - } else if !IsStringEmpty(c.Token) { - r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+c.Token) + return nil +} + +func createCurlCmd(c *Client, r *Request) (err error) { + if r.Debug && r.generateCurlOnDebug { + if r.resultCurlCmd == nil { + r.resultCurlCmd = new(string) + } + *r.resultCurlCmd = buildCurlRequest(r.RawRequest, c.httpClient.Jar) } return nil } func requestLogger(c *Client, r *Request) error { - if c.Debug { + if r.Debug { rr := r.RawRequest - rl := &RequestLog{Header: copyHeaders(rr.Header), Body: r.fmtBodyString(c.debugBodySizeLimit)} + rh := copyHeaders(rr.Header) + if c.GetClient().Jar != nil { + for _, cookie := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { + s := fmt.Sprintf("%s=%s", cookie.Name, cookie.Value) + if c := rh.Get("Cookie"); c != "" { + rh.Set("Cookie", c+"; "+s) + } else { + rh.Set("Cookie", s) + } + } + } + rl := &RequestLog{Header: rh, Body: r.fmtBodyString(c.debugBodySizeLimit)} if c.requestLog != nil { if err := c.requestLog(rl); err != nil { return err } } - // fmt.Sprintf("COOKIES:\n%s\n", composeCookies(c.GetClient().Jar, *rr.URL)) + - reqLog := "\n==============================================================================\n" + - "~~~ REQUEST ~~~\n" + + reqLog := "\n==============================================================================\n" + + if r.Debug && r.generateCurlOnDebug { + reqLog += "~~~ REQUEST(CURL) ~~~\n" + + fmt.Sprintf(" %v\n", *r.resultCurlCmd) + } + + reqLog += "~~~ REQUEST ~~~\n" + fmt.Sprintf("%s %s %s\n", r.Method, rr.URL.RequestURI(), rr.Proto) + fmt.Sprintf("HOST : %s\n", rr.URL.Host) + fmt.Sprintf("HEADERS:\n%s\n", composeHeaders(c, r, rl.Header)) + @@ -290,7 +370,7 @@ func requestLogger(c *Client, r *Request) error { //_______________________________________________________________________ func responseLogger(c *Client, res *Response) error { - if c.Debug { + if res.Request.Debug { rl := &ResponseLog{Header: copyHeaders(res.Header()), Body: res.fmtBodyString(c.debugBodySizeLimit)} if c.responseLog != nil { if err := c.responseLog(rl); err != nil { @@ -301,7 +381,7 @@ func responseLogger(c *Client, res *Response) error { debugLog := res.Request.values[debugRequestLogKey].(string) debugLog += "~~~ RESPONSE ~~~\n" + fmt.Sprintf("STATUS : %s\n", res.Status()) + - fmt.Sprintf("PROTO : %s\n", res.RawResponse.Proto) + + fmt.Sprintf("PROTO : %s\n", res.Proto()) + fmt.Sprintf("RECEIVED AT : %v\n", res.ReceivedAt().Format(time.RFC3339Nano)) + fmt.Sprintf("TIME DURATION: %v\n", res.Time()) + "HEADERS :\n" + @@ -313,7 +393,7 @@ func responseLogger(c *Client, res *Response) error { } debugLog += "==============================================================================\n" - c.log.Debugf("%s", debugLog) + res.Request.log.Debugf("%s", debugLog) } return nil @@ -321,6 +401,7 @@ func responseLogger(c *Client, res *Response) error { func parseResponseBody(c *Client, res *Response) (err error) { if res.StatusCode() == http.StatusNoContent { + res.Request.Error = nil return } // Handles only JSON or XML content type @@ -343,7 +424,10 @@ func parseResponseBody(c *Client, res *Response) (err error) { } if res.Request.Error != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Error) + unmarshalErr := Unmarshalc(c, ct, res.body, res.Request.Error) + if unmarshalErr != nil { + c.log.Warnf("Cannot unmarshal response body: %s", unmarshalErr) + } } } } @@ -351,13 +435,20 @@ func parseResponseBody(c *Client, res *Response) (err error) { return } -func handleMultipart(c *Client, r *Request) (err error) { +func handleMultipart(c *Client, r *Request) error { r.bodyBuf = acquireBuffer() w := multipart.NewWriter(r.bodyBuf) + // Set boundary if not set by user + if r.multipartBoundary != "" { + if err := w.SetBoundary(r.multipartBoundary); err != nil { + return err + } + } + for k, v := range c.FormData { for _, iv := range v { - if err = w.WriteField(k, iv); err != nil { + if err := w.WriteField(k, iv); err != nil { return err } } @@ -366,12 +457,11 @@ func handleMultipart(c *Client, r *Request) (err error) { for k, v := range r.FormData { for _, iv := range v { if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return + if err := addFile(w, k[1:], iv); err != nil { + return err } } else { // form value - if err = w.WriteField(k, iv); err != nil { + if err := w.WriteField(k, iv); err != nil { return err } } @@ -379,55 +469,41 @@ func handleMultipart(c *Client, r *Request) (err error) { } // #21 - adding io.Reader support - if len(r.multipartFiles) > 0 { - for _, f := range r.multipartFiles { - err = addFileReader(w, f) - if err != nil { - return - } + for _, f := range r.multipartFiles { + if err := addFileReader(w, f); err != nil { + return err } } // GitHub #130 adding multipart field support with content type - if len(r.multipartFields) > 0 { - for _, mf := range r.multipartFields { - if err = addMultipartFormField(w, mf); err != nil { - return - } + for _, mf := range r.multipartFields { + if err := addMultipartFormField(w, mf); err != nil { + return err } } r.Header.Set(hdrContentTypeKey, w.FormDataContentType()) - err = w.Close() - - return + return w.Close() } func handleFormData(c *Client, r *Request) { - formData := url.Values{} - for k, v := range c.FormData { - for _, iv := range v { - formData.Add(k, iv) + if _, ok := r.FormData[k]; ok { + continue } + r.FormData[k] = v[:] } - for k, v := range r.FormData { - // remove form data field from client level by key - // since overrides happens for that key in the request - formData.Del(k) - - for _, iv := range v { - formData.Add(k, iv) - } - } - - r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode())) + r.bodyBuf = acquireBuffer() + r.bodyBuf.WriteString(r.FormData.Encode()) r.Header.Set(hdrContentTypeKey, formContentType) r.isFormData = true } func handleContentType(c *Client, r *Request) { + if r.Body == http.NoBody { + return + } contentType := r.Header.Get(hdrContentTypeKey) if IsStringEmpty(contentType) { contentType = DetectContentType(r.Body) @@ -435,45 +511,42 @@ func handleContentType(c *Client, r *Request) { } } -func handleRequestBody(c *Client, r *Request) (err error) { +func handleRequestBody(c *Client, r *Request) error { var bodyBytes []byte - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) r.bodyBuf = nil - if reader, ok := r.Body.(io.Reader); ok { + switch body := r.Body.(type) { + case io.Reader: if c.setContentLength || r.setContentLength { // keep backward compatibility r.bodyBuf = acquireBuffer() - _, err = r.bodyBuf.ReadFrom(reader) + if _, err := r.bodyBuf.ReadFrom(body); err != nil { + return err + } r.Body = nil } else { // Otherwise buffer less processing for `io.Reader`, sounds good. - return - } - } else if b, ok := r.Body.([]byte); ok { - bodyBytes = b - } else if s, ok := r.Body.(string); ok { - bodyBytes = []byte(s) - } else if IsJSONType(contentType) && - (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { - r.bodyBuf, err = jsonMarshal(c, r, r.Body) - if err != nil { - return + return nil + } + case []byte: + bodyBytes = body + case string: + bodyBytes = []byte(body) + default: + contentType := r.Header.Get(hdrContentTypeKey) + kind := kindOf(r.Body) + var err error + if IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { + r.bodyBuf, err = jsonMarshal(c, r, r.Body) + } else if IsXMLType(contentType) && (kind == reflect.Struct) { + bodyBytes, err = c.XMLMarshal(r.Body) } - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - bodyBytes, err = c.XMLMarshal(r.Body) if err != nil { - return + return err } } if bodyBytes == nil && r.bodyBuf == nil { - err = errors.New("unsupported 'Body' type/value") - } - - // if any errors during body bytes handling, return it - if err != nil { - return + return errors.New("unsupported 'Body' type/value") } // []byte into Buffer @@ -482,7 +555,7 @@ func handleRequestBody(c *Client, r *Request) (err error) { _, _ = r.bodyBuf.Write(bodyBytes) } - return + return nil } func saveResponseIntoFile(c *Client, res *Response) error { @@ -521,20 +594,25 @@ func saveResponseIntoFile(c *Client, res *Response) error { func getBodyCopy(r *Request) (*bytes.Buffer, error) { // If r.bodyBuf present, return the copy if r.bodyBuf != nil { - return bytes.NewBuffer(r.bodyBuf.Bytes()), nil + bodyCopy := acquireBuffer() + if _, err := io.Copy(bodyCopy, bytes.NewReader(r.bodyBuf.Bytes())); err != nil { + // cannot use io.Copy(bodyCopy, r.bodyBuf) because io.Copy reset r.bodyBuf + return nil, err + } + return bodyCopy, nil } // Maybe body is `io.Reader`. // Note: Resty user have to watchout for large body size of `io.Reader` if r.RawRequest.Body != nil { - b, err := ioutil.ReadAll(r.RawRequest.Body) + b, err := io.ReadAll(r.RawRequest.Body) if err != nil { return nil, err } // Restore the Body closeq(r.RawRequest.Body) - r.RawRequest.Body = ioutil.NopCloser(bytes.NewBuffer(b)) + r.RawRequest.Body = io.NopCloser(bytes.NewBuffer(b)) // Return the Body bytes return bytes.NewBuffer(b), nil diff --git a/vendor/github.com/go-resty/resty/v2/redirect.go b/vendor/github.com/go-resty/resty/v2/redirect.go index 7d7e43bc13..bb016e2771 100644 --- a/vendor/github.com/go-resty/resty/v2/redirect.go +++ b/vendor/github.com/go-resty/resty/v2/redirect.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -12,18 +12,23 @@ import ( "strings" ) +var ( + ErrAutoRedirectDisabled = errors.New("auto redirect is disabled") +) + type ( - // RedirectPolicy to regulate the redirects in the resty client. - // Objects implementing the RedirectPolicy interface can be registered as + // RedirectPolicy to regulate the redirects in the Resty client. + // Objects implementing the [RedirectPolicy] interface can be registered as // - // Apply function should return nil to continue the redirect jounery, otherwise + // Apply function should return nil to continue the redirect journey; otherwise // return error to stop the redirect. RedirectPolicy interface { Apply(req *http.Request, via []*http.Request) error } - // The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. - // If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f. + // The [RedirectPolicyFunc] type is an adapter to allow the use of ordinary + // functions as [RedirectPolicy]. If `f` is a function with the appropriate + // signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls `f`. RedirectPolicyFunc func(*http.Request, []*http.Request) error ) @@ -32,16 +37,18 @@ func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error return f(req, via) } -// NoRedirectPolicy is used to disable redirects in the HTTP client -// resty.SetRedirectPolicy(NoRedirectPolicy()) +// NoRedirectPolicy is used to disable redirects in the Resty client +// +// resty.SetRedirectPolicy(NoRedirectPolicy()) func NoRedirectPolicy() RedirectPolicy { return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - return errors.New("auto redirect is disabled") + return ErrAutoRedirectDisabled }) } -// FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client. -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) +// FlexibleRedirectPolicy method is convenient for creating several redirect policies for Resty clients. +// +// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { if len(via) >= noOfRedirect { @@ -52,9 +59,10 @@ func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { }) } -// DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. -// Redirect is allowed for only mentioned host in the policy. -// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) +// DomainCheckRedirectPolicy method is convenient for defining domain name redirect rules in Resty clients. +// Redirect is allowed only for the host mentioned in the policy. +// +// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy { hosts := make(map[string]bool) for _, h := range hostnames { @@ -72,10 +80,6 @@ func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy { return fn } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//_______________________________________________________________________ - func getHostname(host string) (hostname string) { if strings.Index(host, ":") > 0 { host, _, _ = net.SplitHostPort(host) @@ -84,10 +88,11 @@ func getHostname(host string) (hostname string) { return } -// By default Golang will not redirect request headers -// after go throughing various discussion comments from thread +// By default, Golang will not redirect request headers. +// After reading through the various discussion comments from the thread - // https://github.com/golang/go/issues/4800 -// Resty will add all the headers during a redirect for the same host +// Resty will add all the headers during a redirect for the same host and +// adds library user-agent if the Host is different. func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) { curHostname := getHostname(cur.URL.Host) preHostname := getHostname(pre.URL.Host) diff --git a/vendor/github.com/go-resty/resty/v2/request.go b/vendor/github.com/go-resty/resty/v2/request.go index 672df88c3e..66f4a82013 100644 --- a/vendor/github.com/go-resty/resty/v2/request.go +++ b/vendor/github.com/go-resty/resty/v2/request.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -23,31 +23,32 @@ import ( // Request struct and methods //_______________________________________________________________________ -// Request struct is used to compose and fire individual request from -// resty client. Request provides an options to override client level -// settings and also an options for the request composition. +// Request struct is used to compose and fire individual requests from +// Resty client. The [Request] provides an option to override client-level +// settings and also an option for the request composition. type Request struct { - URL string - Method string - Token string - AuthScheme string - QueryParam url.Values - FormData url.Values - PathParams map[string]string - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - Cookies []*http.Cookie + URL string + Method string + Token string + AuthScheme string + QueryParam url.Values + FormData url.Values + PathParams map[string]string + RawPathParams map[string]string + Header http.Header + Time time.Time + Body interface{} + Result interface{} + resultCurlCmd *string + Error interface{} + RawRequest *http.Request + SRV *SRVRecord + UserInfo *User + Cookies []*http.Cookie + Debug bool // Attempt is to represent the request attempt made during a Resty // request execution flow, including retry count. - // - // Since v2.4.0 Attempt int isMultiPart bool @@ -65,13 +66,38 @@ type Request struct { client *Client bodyBuf *bytes.Buffer clientTrace *clientTrace + log Logger + multipartBoundary string multipartFiles []*File multipartFields []*MultipartField retryConditions []RetryConditionFunc + responseBodyLimit int + generateCurlOnDebug bool + unescapeQueryParams bool } -// Context method returns the Context if its already set in request -// otherwise it creates new one using `context.Background()`. +// GenerateCurlCommand method generates the CURL command for the request. +func (r *Request) GenerateCurlCommand() string { + if !(r.Debug && r.generateCurlOnDebug) { + return "" + } + + if r.resultCurlCmd != nil { + return *r.resultCurlCmd + } + + if r.RawRequest == nil { + r.client.executeBefore(r) // mock with r.Get("/") + } + if r.resultCurlCmd == nil { + r.resultCurlCmd = new(string) + } + *r.resultCurlCmd = buildCurlRequest(r.RawRequest, r.client.httpClient.Jar) + return *r.resultCurlCmd +} + +// Context method returns the Context if it is already set in the [Request] +// otherwise, it creates a new one using [context.Background]. func (r *Request) Context() context.Context { if r.ctx == nil { return context.Background() @@ -79,38 +105,40 @@ func (r *Request) Context() context.Context { return r.ctx } -// SetContext method sets the context.Context for current Request. It allows -// to interrupt the request execution if ctx.Done() channel is closed. -// See https://blog.golang.org/context article and the "context" package +// SetContext method sets the [context.Context] for current [Request]. It allows +// to interrupt the request execution if `ctx.Done()` channel is closed. +// See https://blog.golang.org/context article and the package [context] // documentation. func (r *Request) SetContext(ctx context.Context) *Request { r.ctx = ctx return r } -// SetHeader method is to set a single header field and its value in the current request. +// SetHeader method sets a single header field and its value in the current request. // // For Example: To set `Content-Type` and `Accept` as `application/json`. -// client.R(). -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") // -// Also you can override header value, which was set at client instance level. +// client.R(). +// SetHeader("Content-Type", "application/json"). +// SetHeader("Accept", "application/json") +// +// It overrides the header value set at the client instance level. func (r *Request) SetHeader(header, value string) *Request { r.Header.Set(header, value) return r } -// SetHeaders method sets multiple headers field and its values at one go in the current request. +// SetHeaders method sets multiple header fields and their values at one go in the current request. // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client.R(). -// SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) -// Also you can override header value, which was set at client instance level. +// client.R(). +// SetHeaders(map[string]string{ +// "Content-Type": "application/json", +// "Accept": "application/json", +// }) +// +// It overrides the header value set at the client instance level. func (r *Request) SetHeaders(headers map[string]string) *Request { for h, v := range headers { r.SetHeader(h, v) @@ -118,15 +146,16 @@ func (r *Request) SetHeaders(headers map[string]string) *Request { return r } -// SetHeaderMultiValues sets multiple headers fields and its values is list of strings at one go in the current request. +// SetHeaderMultiValues sets multiple header fields and their values as a list of strings in the current request. // // For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8` // -// client.R(). -// SetHeaderMultiValues(map[string][]string{ -// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}, -// }) -// Also you can override header value, which was set at client instance level. +// client.R(). +// SetHeaderMultiValues(map[string][]string{ +// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}, +// }) +// +// It overrides the header value set at the client instance level. func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { for key, values := range headers { r.SetHeader(key, strings.Join(values, ", ")) @@ -134,44 +163,47 @@ func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { return r } -// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. +// SetHeaderVerbatim method sets a single header field and its value verbatim in the current request. // // For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") // -// Also you can override header value, which was set at client instance level. +// client.R(). +// SetHeaderVerbatim("all_lowercase", "available"). +// SetHeaderVerbatim("UPPERCASE", "available") // -// Since v2.6.0 +// It overrides the header value set at the client instance level. func (r *Request) SetHeaderVerbatim(header, value string) *Request { r.Header[header] = []string{value} return r } -// SetQueryParam method sets single parameter and its value in the current request. -// It will be formed as query string for the request. +// SetQueryParam method sets a single parameter and its value in the current request. +// It will be formed as a query string for the request. +// +// For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark. // -// For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") -// Also you can override query params value, which was set at client instance level. +// client.R(). +// SetQueryParam("search", "kitchen papers"). +// SetQueryParam("size", "large") +// +// It overrides the query parameter value set at the client instance level. func (r *Request) SetQueryParam(param, value string) *Request { r.QueryParam.Set(param, value) return r } -// SetQueryParams method sets multiple parameters and its values at one go in the current request. -// It will be formed as query string for the request. +// SetQueryParams method sets multiple parameters and their values at one go in the current request. +// It will be formed as a query string for the request. // -// For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) -// Also you can override query params value, which was set at client instance level. +// For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark. +// +// client.R(). +// SetQueryParams(map[string]string{ +// "search": "kitchen papers", +// "size": "large", +// }) +// +// It overrides the query parameter value set at the client instance level. func (r *Request) SetQueryParams(params map[string]string) *Request { for p, v := range params { r.SetQueryParam(p, v) @@ -179,16 +211,29 @@ func (r *Request) SetQueryParams(params map[string]string) *Request { return r } +// SetUnescapeQueryParams method sets the unescape query parameters choice for request URL. +// To prevent broken URL, resty replaces space (" ") with "+" in the query parameters. +// +// This method overrides the value set by [Client.SetUnescapeQueryParams] +// +// NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters. +func (r *Request) SetUnescapeQueryParams(unescape bool) *Request { + r.unescapeQueryParams = unescape + return r +} + // SetQueryParamsFromValues method appends multiple parameters with multi-value -// (`url.Values`) at one go in the current request. It will be formed as +// ([url.Values]) at one go in the current request. It will be formed as // query string for the request. // -// For Example: `status=pending&status=approved&status=open` in the URL after `?` mark. -// client.R(). -// SetQueryParamsFromValues(url.Values{ -// "status": []string{"pending", "approved", "open"}, -// }) -// Also you can override query params value, which was set at client instance level. +// For Example: `status=pending&status=approved&status=open` in the URL after the `?` mark. +// +// client.R(). +// SetQueryParamsFromValues(url.Values{ +// "status": []string{"pending", "approved", "open"}, +// }) +// +// It overrides the query parameter value set at the client instance level. func (r *Request) SetQueryParamsFromValues(params url.Values) *Request { for p, v := range params { for _, pv := range v { @@ -198,11 +243,12 @@ func (r *Request) SetQueryParamsFromValues(params url.Values) *Request { return r } -// SetQueryString method provides ability to use string as an input to set URL query string for the request. +// SetQueryString method provides the ability to use string as an input to set URL query string for the request. +// +// client.R(). +// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") // -// Using String as an input -// client.R(). -// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") +// It overrides the query parameter value set at the client instance level. func (r *Request) SetQueryString(query string) *Request { params, err := url.ParseQuery(strings.TrimSpace(query)) if err == nil { @@ -212,20 +258,22 @@ func (r *Request) SetQueryString(query string) *Request { } } } else { - r.client.log.Errorf("%v", err) + r.log.Errorf("%v", err) } return r } -// SetFormData method sets Form parameters and their values in the current request. -// It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as -// `application/x-www-form-urlencoded`. -// client.R(). -// SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) -// Also you can override form data value, which was set at client instance level. +// SetFormData method sets Form parameters and their values for the current request. +// It applies only to HTTP methods `POST` and `PUT`, and by default requests +// content type would be set as `application/x-www-form-urlencoded`. +// +// client.R(). +// SetFormData(map[string]string{ +// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", +// "user_id": "3455454545", +// }) +// +// It overrides the form data value set at the client instance level. func (r *Request) SetFormData(data map[string]string) *Request { for k, v := range data { r.FormData.Set(k, v) @@ -234,12 +282,14 @@ func (r *Request) SetFormData(data map[string]string) *Request { } // SetFormDataFromValues method appends multiple form parameters with multi-value -// (`url.Values`) at one go in the current request. -// client.R(). -// SetFormDataFromValues(url.Values{ -// "search_criteria": []string{"book", "glass", "pencil"}, -// }) -// Also you can override form data value, which was set at client instance level. +// ([url.Values]) at one go in the current request. +// +// client.R(). +// SetFormDataFromValues(url.Values{ +// "search_criteria": []string{"book", "glass", "pencil"}, +// }) +// +// It overrides the form data value set at the client instance level. func (r *Request) SetFormDataFromValues(data url.Values) *Request { for k, v := range data { for _, kv := range v { @@ -249,80 +299,110 @@ func (r *Request) SetFormDataFromValues(data url.Values) *Request { return r } -// SetBody method sets the request body for the request. It supports various realtime needs as easy. -// We can say its quite handy or powerful. Supported request body data types is `string`, -// `[]byte`, `struct`, `map`, `slice` and `io.Reader`. Body value can be pointer or non-pointer. -// Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`. +// SetBody method sets the request body for the request. It supports various practical needs as easy. +// It's quite handy and powerful. Supported request body data types are `string`, +// `[]byte`, `struct`, `map`, `slice` and [io.Reader]. // -// Note: `io.Reader` is processed as bufferless mode while sending request. +// Body value can be pointer or non-pointer. Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`. // -// For Example: Struct as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(User{ -// Username: "jeeva@myjeeva.com", -// Password: "welcome2resty", -// }) +// NOTE: [io.Reader] is processed in bufferless mode while sending a request. // -// Map as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(map[string]interface{}{ -// "username": "jeeva@myjeeva.com", -// "password": "welcome2resty", -// "address": &Address{ -// Address1: "1111 This is my street", -// Address2: "Apt 201", -// City: "My City", -// State: "My State", -// ZipCode: 00000, -// }, -// }) +// For Example: // -// String as a body input. Suitable for any need as a string input. -// client.R(). -// SetBody(`{ -// "username": "jeeva@getrightcare.com", -// "password": "admin" -// }`) +// `struct` gets marshaled based on the request header `Content-Type`. // -// []byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc. -// client.R(). -// SetBody([]byte("This is my raw request, sent as-is")) +// client.R(). +// SetBody(User{ +// Username: "jeeva@myjeeva.com", +// Password: "welcome2resty", +// }) +// +// 'map` gets marshaled based on the request header `Content-Type`. +// +// client.R(). +// SetBody(map[string]interface{}{ +// "username": "jeeva@myjeeva.com", +// "password": "welcome2resty", +// "address": &Address{ +// Address1: "1111 This is my street", +// Address2: "Apt 201", +// City: "My City", +// State: "My State", +// ZipCode: 00000, +// }, +// }) +// +// `string` as a body input. Suitable for any need as a string input. +// +// client.R(). +// SetBody(`{ +// "username": "jeeva@getrightcare.com", +// "password": "admin" +// }`) +// +// `[]byte` as a body input. Suitable for raw requests such as file upload, serialize & deserialize, etc. +// +// client.R(). +// SetBody([]byte("This is my raw request, sent as-is")) +// +// and so on. func (r *Request) SetBody(body interface{}) *Request { r.Body = body return r } -// SetResult method is to register the response `Result` object for automatic unmarshalling for the request, -// if response status code is between 200 and 299 and content type either JSON or XML. +// SetResult method is to register the response `Result` object for automatic +// unmarshalling of the HTTP response if the response status code is +// between 200 and 299, and the content type is JSON or XML. // -// Note: Result object can be pointer or non-pointer. -// client.R().SetResult(&AuthToken{}) -// // OR -// client.R().SetResult(AuthToken{}) +// Note: [Request.SetResult] input can be a pointer or non-pointer. // -// Accessing a result value from response instance. -// response.Result().(*AuthToken) +// The pointer with handle +// +// authToken := &AuthToken{} +// client.R().SetResult(authToken) +// +// // Can be accessed via - +// fmt.Println(authToken) OR fmt.Println(response.Result().(*AuthToken)) +// +// OR - +// +// The pointer without handle or non-pointer +// +// client.R().SetResult(&AuthToken{}) +// // OR +// client.R().SetResult(AuthToken{}) +// +// // Can be accessed via - +// fmt.Println(response.Result().(*AuthToken)) func (r *Request) SetResult(res interface{}) *Request { - r.Result = getPointer(res) + if res != nil { + r.Result = getPointer(res) + } return r } // SetError method is to register the request `Error` object for automatic unmarshalling for the request, -// if response status code is greater than 399 and content type either JSON or XML. +// if the response status code is greater than 399 and the content type is either JSON or XML. // -// Note: Error object can be pointer or non-pointer. -// client.R().SetError(&AuthError{}) -// // OR -// client.R().SetError(AuthError{}) +// NOTE: [Request.SetError] input can be a pointer or non-pointer. // -// Accessing a error value from response instance. -// response.Error().(*AuthError) +// client.R().SetError(&AuthError{}) +// // OR +// client.R().SetError(AuthError{}) +// +// Accessing an error value from response instance. +// +// response.Error().(*AuthError) +// +// If this request Error object is nil, Resty will use the client-level error object Type if it is set. func (r *Request) SetError(err interface{}) *Request { r.Error = getPointer(err) return r } -// SetFile method is to set single file field name and its path for multipart upload. +// SetFile method sets a single file field name and its path for multipart upload. +// // client.R(). // SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf") func (r *Request) SetFile(param, filePath string) *Request { @@ -331,7 +411,8 @@ func (r *Request) SetFile(param, filePath string) *Request { return r } -// SetFiles method is to set multiple file field name and its path for multipart upload. +// SetFiles method sets multiple file field names and their paths for multipart uploads. +// // client.R(). // SetFiles(map[string]string{ // "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf", @@ -346,7 +427,8 @@ func (r *Request) SetFiles(files map[string]string) *Request { return r } -// SetFileReader method is to set single file using io.Reader for multipart upload. +// SetFileReader method is to set a file using [io.Reader] for multipart upload. +// // client.R(). // SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)). // SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes)) @@ -360,7 +442,8 @@ func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Reque return r } -// SetMultipartFormData method allows simple form data to be attached to the request as `multipart:form-data` +// SetMultipartFormData method allows simple form data to be attached to the request +// as `multipart:form-data` func (r *Request) SetMultipartFormData(data map[string]string) *Request { for k, v := range data { r = r.SetMultipartField(k, "", "", strings.NewReader(v)) @@ -369,7 +452,7 @@ func (r *Request) SetMultipartFormData(data map[string]string) *Request { return r } -// SetMultipartField method is to set custom data using io.Reader for multipart upload. +// SetMultipartField method sets custom data with Content-Type using [io.Reader] for multipart upload. func (r *Request) SetMultipartField(param, fileName, contentType string, reader io.Reader) *Request { r.isMultiPart = true r.multipartFields = append(r.multipartFields, &MultipartField{ @@ -381,11 +464,12 @@ func (r *Request) SetMultipartField(param, fileName, contentType string, reader return r } -// SetMultipartFields method is to set multiple data fields using io.Reader for multipart upload. +// SetMultipartFields method sets multiple data fields using [io.Reader] for multipart upload. // // For Example: -// client.R().SetMultipartFields( -// &resty.MultipartField{ +// +// client.R().SetMultipartFields( +// &resty.MultipartField{ // Param: "uploadManifest1", // FileName: "upload-file-1.json", // ContentType: "application/json", @@ -398,20 +482,30 @@ func (r *Request) SetMultipartField(param, fileName, contentType string, reader // Reader: strings.NewReader(`{"input": {"name": "Uploaded document 2", "_filename" : ["file2.txt"]}}`), // }) // -// If you have slice already, then simply call- -// client.R().SetMultipartFields(fields...) +// If you have a `slice` of fields already, then call- +// +// client.R().SetMultipartFields(fields...) func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request { r.isMultiPart = true r.multipartFields = append(r.multipartFields, fields...) return r } -// SetContentLength method sets the HTTP header `Content-Length` value for current request. -// By default Resty won't set `Content-Length`. Also you have an option to enable for every -// request. +// SetMultipartBoundary method sets the custom multipart boundary for the multipart request. +// Typically, the `mime/multipart` package generates a random multipart boundary if not provided. +func (r *Request) SetMultipartBoundary(boundary string) *Request { + r.multipartBoundary = boundary + return r +} + +// SetContentLength method sets the current request's HTTP header `Content-Length` value. +// By default, Resty won't set `Content-Length`. // -// See `Client.SetContentLength` -// client.R().SetContentLength(true) +// See [Client.SetContentLength] +// +// client.R().SetContentLength(true) +// +// It overrides the value set at the client instance level. func (r *Request) SetContentLength(l bool) *Request { r.setContentLength = l return r @@ -420,60 +514,100 @@ func (r *Request) SetContentLength(l bool) *Request { // SetBasicAuth method sets the basic authentication header in the current HTTP request. // // For Example: -// Authorization: Basic +// +// Authorization: Basic // // To set the header for username "go-resty" and password "welcome" -// client.R().SetBasicAuth("go-resty", "welcome") // -// This method overrides the credentials set by method `Client.SetBasicAuth`. +// client.R().SetBasicAuth("go-resty", "welcome") +// +// It overrides the credentials set by method [Client.SetBasicAuth]. func (r *Request) SetBasicAuth(username, password string) *Request { r.UserInfo = &User{Username: username, Password: password} return r } // SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example: -// Authorization: Bearer +// +// Authorization: Bearer // // For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F // -// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") +// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // -// This method overrides the Auth token set by method `Client.SetAuthToken`. +// It overrides the Auth token set by method [Client.SetAuthToken]. func (r *Request) SetAuthToken(token string) *Request { r.Token = token return r } -// SetAuthScheme method sets the auth token scheme type in the HTTP request. For Example: -// Authorization: +// SetAuthScheme method sets the auth token scheme type in the HTTP request. +// +// Example Header value structure: +// +// Authorization: // // For Example: To set the scheme to use OAuth // -// client.R().SetAuthScheme("OAuth") +// client.R().SetAuthScheme("OAuth") +// +// // The outcome will be - +// Authorization: OAuth // -// This auth header scheme gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. +// Information about Auth schemes can be found in [RFC 7235], IANA [HTTP Auth schemes] // -// Information about Auth schemes can be found in RFC7235 which is linked to below along with the page containing -// the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// It overrides the `Authorization` scheme set by method [Client.SetAuthScheme]. // -// This method overrides the Authorization scheme set by method `Client.SetAuthScheme`. +// [RFC 7235]: https://tools.ietf.org/html/rfc7235 +// [HTTP Auth schemes]: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes func (r *Request) SetAuthScheme(scheme string) *Request { r.AuthScheme = scheme return r } -// SetOutput method sets the output file for current HTTP request. Current HTTP response will be -// saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. -// If is it relative path then output file goes under the output directory, as mentioned -// in the `Client.SetOutputDirectory`. -// client.R(). -// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). -// Get("http://bit.ly/1LouEKr") +// SetDigestAuth method sets the Digest Access auth scheme for the HTTP request. +// If a server responds with 401 and sends a Digest challenge in the WWW-Authenticate Header, +// the request will be resent with the appropriate Authorization Header. +// +// For Example: To set the Digest scheme with username "Mufasa" and password "Circle Of Life" +// +// client.R().SetDigestAuth("Mufasa", "Circle Of Life") +// +// Information about Digest Access Authentication can be found in [RFC 7616] +// +// It overrides the digest username and password set by method [Client.SetDigestAuth]. +// +// [RFC 7616]: https://datatracker.ietf.org/doc/html/rfc7616 +func (r *Request) SetDigestAuth(username, password string) *Request { + oldTransport := r.client.httpClient.Transport + r.client.OnBeforeRequest(func(c *Client, _ *Request) error { + c.httpClient.Transport = &digestTransport{ + digestCredentials: digestCredentials{username, password}, + transport: oldTransport, + } + return nil + }) + r.client.OnAfterResponse(func(c *Client, _ *Response) error { + c.httpClient.Transport = oldTransport + return nil + }) + + return r +} + +// SetOutput method sets the output file for the current HTTP request. The current +// HTTP response will be saved in the given file. It is similar to the `curl -o` flag. +// +// Absolute path or relative path can be used. +// +// If it is a relative path, then the output file goes under the output directory, as mentioned +// in the [Client.SetOutputDirectory]. // -// Note: In this scenario `Response.Body` might be nil. +// client.R(). +// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). +// Get("http://bit.ly/1LouEKr") +// +// NOTE: In this scenario [Response.Body] might be nil. func (r *Request) SetOutput(file string) *Request { r.outputFile = file r.isSaveResponse = true @@ -482,34 +616,62 @@ func (r *Request) SetOutput(file string) *Request { // SetSRV method sets the details to query the service SRV record and execute the // request. -// client.R(). -// SetSRV(SRVRecord{"web", "testservice.com"}). -// Get("/get") +// +// client.R(). +// SetSRV(SRVRecord{"web", "testservice.com"}). +// Get("/get") func (r *Request) SetSRV(srv *SRVRecord) *Request { r.SRV = srv return r } -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. +// SetDoNotParseResponse method instructs Resty not to parse the response body automatically. +// Resty exposes the raw response body as [io.ReadCloser]. If you use it, do not +// forget to close the body, otherwise, you might get into connection leaks, and connection +// reuse may not happen. // -// Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. +// NOTE: [Response] middlewares are not executed using this option. You have +// taken over the control of response parsing from Resty. func (r *Request) SetDoNotParseResponse(parse bool) *Request { r.notParseResponse = parse return r } -// SetPathParam method sets single URL path key-value pair in the +// SetResponseBodyLimit method sets a maximum body size limit in bytes on response, +// avoid reading too much data to memory. +// +// Client will return [resty.ErrResponseBodyTooLarge] if the body size of the body +// in the uncompressed response is larger than the limit. +// Body size limit will not be enforced in the following cases: +// - ResponseBodyLimit <= 0, which is the default behavior. +// - [Request.SetOutput] is called to save response data to the file. +// - "DoNotParseResponse" is set for client or request. +// +// It overrides the value set at the client instance level. see [Client.SetResponseBodyLimit] +func (r *Request) SetResponseBodyLimit(v int) *Request { + r.responseBodyLimit = v + return r +} + +// SetPathParam method sets a single URL path key-value pair in the // Resty current request instance. -// client.R().SetPathParam("userId", "sample@sample.com") // -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// It replaces the value of the key while composing the request URL. Also you can -// override Path Params value, which was set at client instance level. +// client.R().SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.R().SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing the request URL. +// The values will be escaped using function [url.PathEscape]. +// +// It overrides the path parameter set at the client instance level. func (r *Request) SetPathParam(param, value string) *Request { r.PathParams[param] = value return r @@ -517,16 +679,21 @@ func (r *Request) SetPathParam(param, value string) *Request { // SetPathParams method sets multiple URL path key-value pairs at one go in the // Resty current request instance. -// client.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replaces the value of the key while composing request URL. Also you can -// override Path Params value, which was set at client instance level. +// +// client.R().SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing the request URL. +// The values will be escaped using function [url.PathEscape]. +// +// It overrides the path parameter set at the client instance level. func (r *Request) SetPathParams(params map[string]string) *Request { for p, v := range params { r.SetPathParam(p, v) @@ -534,73 +701,150 @@ func (r *Request) SetPathParams(params map[string]string) *Request { return r } +// SetRawPathParam method sets a single URL path key-value pair in the +// Resty current request instance. +// +// client.R().SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.R().SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups/developers/details +// +// It replaces the value of the key while composing the request URL. +// The value will be used as-is and has not been escaped. +// +// It overrides the raw path parameter set at the client instance level. +func (r *Request) SetRawPathParam(param, value string) *Request { + r.RawPathParams[param] = value + return r +} + +// SetRawPathParams method sets multiple URL path key-value pairs at one go in the +// Resty current request instance. +// +// client.R().SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details +// +// It replaces the value of the key while composing the request URL. +// The value will be used as-is and has not been escaped. +// +// It overrides the raw path parameter set at the client instance level. +func (r *Request) SetRawPathParams(params map[string]string) *Request { + for p, v := range params { + r.SetRawPathParam(p, v) + } + return r +} + // ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling -// when `Content-Type` response header is unavailable. +// when the `Content-Type` response header is unavailable. func (r *Request) ExpectContentType(contentType string) *Request { r.fallbackContentType = contentType return r } -// ForceContentType method provides a strong sense of response `Content-Type` for automatic unmarshalling. -// Resty gives this a higher priority than the `Content-Type` response header. This means that if both -// `Request.ForceContentType` is set and the response `Content-Type` is available, `ForceContentType` will win. +// ForceContentType method provides a strong sense of response `Content-Type` for +// automatic unmarshalling. Resty gives this a higher priority than the `Content-Type` +// response header. +// +// This means that if both [Request.ForceContentType] is set and +// the response `Content-Type` is available, `ForceContentType` will win. func (r *Request) ForceContentType(contentType string) *Request { r.forceContentType = contentType return r } -// SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. +// SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. +// By default, escape HTML is false. // -// Note: This option only applicable to standard JSON Marshaller. +// NOTE: This option only applies to the standard JSON Marshaller used by Resty. +// +// It overrides the value set at the client instance level, see [Client.SetJSONEscapeHTML] func (r *Request) SetJSONEscapeHTML(b bool) *Request { r.jsonEscapeHTML = b return r } // SetCookie method appends a single cookie in the current request instance. -// client.R().SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) // -// Note: Method appends the Cookie value into existing Cookie if already existing. +// client.R().SetCookie(&http.Cookie{ +// Name:"go-resty", +// Value:"This is cookie value", +// }) // -// Since v2.1.0 +// NOTE: Method appends the Cookie value into existing Cookie even if its already existing. func (r *Request) SetCookie(hc *http.Cookie) *Request { r.Cookies = append(r.Cookies, hc) return r } // SetCookies method sets an array of cookies in the current request instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty's current request -// client.R().SetCookies(cookies) -// -// Note: Method appends the Cookie value into existing Cookie if already existing. -// -// Since v2.1.0 +// +// cookies := []*http.Cookie{ +// &http.Cookie{ +// Name:"go-resty-1", +// Value:"This is cookie 1 value", +// }, +// &http.Cookie{ +// Name:"go-resty-2", +// Value:"This is cookie 2 value", +// }, +// } +// +// // Setting a cookies into resty's current request +// client.R().SetCookies(cookies) +// +// NOTE: Method appends the Cookie value into existing Cookie even if its already existing. func (r *Request) SetCookies(rs []*http.Cookie) *Request { r.Cookies = append(r.Cookies, rs...) return r } -// AddRetryCondition method adds a retry condition function to the request's -// array of functions that are checked to determine if the request is retried. -// The request will retry if any of the functions return true and error is nil. +// SetLogger method sets given writer for logging Resty request and response details. +// By default, requests and responses inherit their logger from the client. // -// Note: These retry conditions are checked before all retry conditions of the client. +// Compliant to interface [resty.Logger]. // -// Since v2.7.0 +// It overrides the logger value set at the client instance level. +func (r *Request) SetLogger(l Logger) *Request { + r.log = l + return r +} + +// SetDebug method enables the debug mode on the current request. It logs +// the details current request and response. +// +// client.SetDebug(true) +// +// Also, it can be enabled at the request level for a particular request; see [Request.SetDebug]. +// - For [Request], it logs information such as HTTP verb, Relative URL path, +// Host, Headers, and Body if it has one. +// - For [Response], it logs information such as Status, Response Time, Headers, +// and Body if it has one. +func (r *Request) SetDebug(d bool) *Request { + r.Debug = d + return r +} + +// AddRetryCondition method adds a retry condition function to the request's +// array of functions is checked to determine if the request can be retried. +// The request will retry if any functions return true and the error is nil. +// +// NOTE: The request level retry conditions are checked before all retry +// conditions from the client instance. func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { r.retryConditions = append(r.retryConditions, condition) return r @@ -611,27 +855,41 @@ func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { //_______________________________________________________________________ // EnableTrace method enables trace for the current request -// using `httptrace.ClientTrace` and provides insights. -// -// client := resty.New() +// using [httptrace.ClientTrace] and provides insights. // -// resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) +// client := resty.New() // -// See `Client.EnableTrace` available too to get trace info for all requests. +// resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") +// fmt.Println("Error:", err) +// fmt.Println("Trace Info:", resp.Request.TraceInfo()) // -// Since v2.0.0 +// See [Client.EnableTrace] is also available to get trace info for all requests. func (r *Request) EnableTrace() *Request { r.trace = true return r } -// TraceInfo method returns the trace info for the request. -// If either the Client or Request EnableTrace function has not been called -// prior to the request being made, an empty TraceInfo object will be returned. +// EnableGenerateCurlOnDebug method enables the generation of CURL commands in the debug log. +// It works in conjunction with debug mode. It overrides the options set by the [Client]. // -// Since v2.0.0 +// NOTE: Use with care. +// - Potential to leak sensitive data from [Request] and [Response] in the debug log. +// - Beware of memory usage since the request body is reread. +func (r *Request) EnableGenerateCurlOnDebug() *Request { + r.generateCurlOnDebug = true + return r +} + +// DisableGenerateCurlOnDebug method disables the option set by [Request.EnableGenerateCurlOnDebug]. +// It overrides the options set by the [Client]. +func (r *Request) DisableGenerateCurlOnDebug() *Request { + r.generateCurlOnDebug = false + return r +} + +// TraceInfo method returns the trace info for the request. +// If either the [Client.EnableTrace] or [Request.EnableTrace] function has not been called +// before the request is made, an empty [resty.TraceInfo] object is returned. func (r *Request) TraceInfo() TraceInfo { ct := r.clientTrace @@ -639,23 +897,41 @@ func (r *Request) TraceInfo() TraceInfo { return TraceInfo{} } + ct.lock.RLock() + defer ct.lock.RUnlock() + ti := TraceInfo{ - DNSLookup: ct.dnsDone.Sub(ct.dnsStart), - TLSHandshake: ct.tlsHandshakeDone.Sub(ct.tlsHandshakeStart), - ServerTime: ct.gotFirstResponseByte.Sub(ct.gotConn), + DNSLookup: 0, + TCPConnTime: 0, + ServerTime: 0, IsConnReused: ct.gotConnInfo.Reused, IsConnWasIdle: ct.gotConnInfo.WasIdle, ConnIdleTime: ct.gotConnInfo.IdleTime, RequestAttempt: r.Attempt, } - // Calculate the total time accordingly, - // when connection is reused - if ct.gotConnInfo.Reused { - ti.TotalTime = ct.endTime.Sub(ct.getConn) - } else { - ti.TotalTime = ct.endTime.Sub(ct.dnsStart) + if !ct.dnsStart.IsZero() && !ct.dnsDone.IsZero() { + ti.DNSLookup = ct.dnsDone.Sub(ct.dnsStart) + } + + if !ct.tlsHandshakeDone.IsZero() && !ct.tlsHandshakeStart.IsZero() { + ti.TLSHandshake = ct.tlsHandshakeDone.Sub(ct.tlsHandshakeStart) + } + + if !ct.gotFirstResponseByte.IsZero() && !ct.gotConn.IsZero() { + ti.ServerTime = ct.gotFirstResponseByte.Sub(ct.gotConn) + } + + // Calculate the total time accordingly when connection is reused, + // and DNS start and get conn time may be zero if the request is invalid. + // See issue #1016. + requestStartTime := r.Time + if ct.gotConnInfo.Reused && !ct.getConn.IsZero() { + requestStartTime = ct.getConn + } else if !ct.dnsStart.IsZero() { + requestStartTime = ct.dnsStart } + ti.TotalTime = ct.endTime.Sub(requestStartTime) // Only calculate on successful connections if !ct.connectDone.IsZero() { @@ -720,26 +996,41 @@ func (r *Request) Patch(url string) (*Response, error) { } // Send method performs the HTTP request using the method and URL already defined -// for current `Request`. -// req := client.R() -// req.Method = resty.GET -// req.URL = "http://httpbin.org/get" -// resp, err := client.R().Send() +// for current [Request]. +// +// req := client.R() +// req.Method = resty.MethodGet +// req.URL = "http://httpbin.org/get" +// resp, err := req.Send() func (r *Request) Send() (*Response, error) { return r.Execute(r.Method, r.URL) } -// Execute method performs the HTTP request with given HTTP method and URL -// for current `Request`. -// resp, err := client.R().Execute(resty.GET, "http://httpbin.org/get") +// Execute method performs the HTTP request with the given HTTP method and URL +// for current [Request]. +// +// resp, err := client.R().Execute(resty.MethodGet, "http://httpbin.org/get") func (r *Request) Execute(method, url string) (*Response, error) { var addrs []*net.SRV var resp *Response var err error + defer func() { + if rec := recover(); rec != nil { + if err, ok := rec.(error); ok { + r.client.onPanicHooks(r, err) + } else { + r.client.onPanicHooks(r, fmt.Errorf("panic %v", rec)) + } + panic(rec) + } + }() + if r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) { // No OnError hook here since this is a request validation error - return nil, fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) + err := fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) + r.client.onInvalidHooks(r, err) + return nil, err } if r.SRV != nil { @@ -757,6 +1048,7 @@ func (r *Request) Execute(method, url string) (*Response, error) { r.Attempt = 1 resp, err = r.client.execute(r) r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) + backToBufPool(r.bodyBuf) return resp, unwrapNoRetryErr(err) } @@ -768,7 +1060,7 @@ func (r *Request) Execute(method, url string) (*Response, error) { resp, err = r.client.execute(r) if err != nil { - r.client.log.Errorf("%v, Attempt %v", err, r.Attempt) + r.log.Warnf("%v, Attempt %v", err, r.Attempt) } return resp, err @@ -778,10 +1070,15 @@ func (r *Request) Execute(method, url string) (*Response, error) { MaxWaitTime(r.client.RetryMaxWaitTime), RetryConditions(append(r.retryConditions, r.client.RetryConditions...)), RetryHooks(r.client.RetryHooks), + ResetMultipartReaders(r.client.RetryResetReaders), ) - r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) + if err != nil { + r.log.Errorf("%v", err) + } + r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) + backToBufPool(r.bodyBuf) return resp, unwrapNoRetryErr(err) } @@ -796,13 +1093,10 @@ type SRVRecord struct { Domain string } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Unexported methods -//_______________________________________________________________________ - func (r *Request) fmtBodyString(sl int64) (body string) { body = "***** NO CONTENT *****" - if !isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) { + if !isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) || + r.Body == http.NoBody { return } @@ -832,7 +1126,12 @@ func (r *Request) fmtBodyString(sl int64) (body string) { contentType := r.Header.Get(hdrContentTypeKey) kind := kindOf(r.Body) if canJSONMarshal(contentType, kind) { - prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ") + var bodyBuf *bytes.Buffer + bodyBuf, err = noescapeJSONMarshalIndent(&r.Body) + if err == nil { + prtBodyBytes = bodyBuf.Bytes() + defer releaseBuffer(bodyBuf) + } } else if IsXMLType(contentType) && (kind == reflect.Struct) { prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ") } else if b, ok := r.Body.(string); ok { @@ -894,3 +1193,17 @@ var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) { return buf, nil } + +var noescapeJSONMarshalIndent = func(v interface{}) (*bytes.Buffer, error) { + buf := acquireBuffer() + encoder := json.NewEncoder(buf) + encoder.SetEscapeHTML(false) + encoder.SetIndent("", " ") + + if err := encoder.Encode(v); err != nil { + releaseBuffer(buf) + return nil, err + } + + return buf, nil +} diff --git a/vendor/github.com/go-resty/resty/v2/response.go b/vendor/github.com/go-resty/resty/v2/response.go index 8ae0e10bac..f52b5c61ff 100644 --- a/vendor/github.com/go-resty/resty/v2/response.go +++ b/vendor/github.com/go-resty/resty/v2/response.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -17,7 +17,7 @@ import ( // Response struct and methods //_______________________________________________________________________ -// Response struct holds response values of executed request. +// Response struct holds response values of executed requests. type Response struct { Request *Request RawResponse *http.Response @@ -27,9 +27,10 @@ type Response struct { receivedAt time.Time } -// Body method returns HTTP response as []byte array for the executed request. +// Body method returns the HTTP response as `[]byte` slice for the executed request. // -// Note: `Response.Body` might be nil, if `Request.SetOutput` is used. +// NOTE: [Response.Body] might be nil if [Request.SetOutput] is used. +// Also see [Request.SetDoNotParseResponse], [Client.SetDoNotParseResponse] func (r *Response) Body() []byte { if r.RawResponse == nil { return []byte{} @@ -37,7 +38,18 @@ func (r *Response) Body() []byte { return r.body } +// SetBody method sets [Response] body in byte slice. Typically, +// It is helpful for test cases. +// +// resp.SetBody([]byte("This is test body content")) +// resp.SetBody(nil) +func (r *Response) SetBody(b []byte) *Response { + r.body = b + return r +} + // Status method returns the HTTP status string for the executed request. +// // Example: 200 OK func (r *Response) Status() string { if r.RawResponse == nil { @@ -47,6 +59,7 @@ func (r *Response) Status() string { } // StatusCode method returns the HTTP status code for the executed request. +// // Example: 200 func (r *Response) StatusCode() int { if r.RawResponse == nil { @@ -64,11 +77,15 @@ func (r *Response) Proto() string { } // Result method returns the response value as an object if it has one +// +// See [Request.SetResult] func (r *Response) Result() interface{} { return r.Request.Result } // Error method returns the error object if it has one +// +// See [Request.SetError], [Client.SetError] func (r *Response) Error() interface{} { return r.Request.Error } @@ -81,7 +98,7 @@ func (r *Response) Header() http.Header { return r.RawResponse.Header } -// Cookies method to access all the response cookies +// Cookies method to returns all the response cookies func (r *Response) Cookies() []*http.Cookie { if r.RawResponse == nil { return make([]*http.Cookie, 0) @@ -89,18 +106,20 @@ func (r *Response) Cookies() []*http.Cookie { return r.RawResponse.Cookies() } -// String method returns the body of the server response as String. +// String method returns the body of the HTTP response as a `string`. +// It returns an empty string if it is nil or the body is zero length. func (r *Response) String() string { - if r.body == nil { + if len(r.body) == 0 { return "" } return strings.TrimSpace(string(r.body)) } -// Time method returns the time of HTTP response time that from request we sent and received a request. +// Time method returns the duration of HTTP response time from the request we sent +// and received a request. // -// See `Response.ReceivedAt` to know when client received response and see `Response.Request.Time` to know -// when client sent a request. +// See [Response.ReceivedAt] to know when the client received a response and see +// `Response.Request.Time` to know when the client sent a request. func (r *Response) Time() time.Duration { if r.Request.clientTrace != nil { return r.Request.TraceInfo().TotalTime @@ -108,23 +127,25 @@ func (r *Response) Time() time.Duration { return r.receivedAt.Sub(r.Request.Time) } -// ReceivedAt method returns when response got received from server for the request. +// ReceivedAt method returns the time we received a response from the server for the request. func (r *Response) ReceivedAt() time.Time { return r.receivedAt } -// Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header, -// however it won't be good for chucked transfer/compressed response. Since Resty calculates response size -// at the client end. You will get actual size of the http response. +// Size method returns the HTTP response size in bytes. Yeah, you can rely on HTTP `Content-Length` +// header, however it won't be available for chucked transfer/compressed response. +// Since Resty captures response size details when processing the response body +// when possible. So that users get the actual size of response bytes. func (r *Response) Size() int64 { return r.size } -// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` -// option otherwise you get an error as `read err: http: read on closed response body`. +// RawBody method exposes the HTTP raw response body. Use this method in conjunction with +// [Client.SetDoNotParseResponse] or [Request.SetDoNotParseResponse] +// option; otherwise, you get an error as `read err: http: read on closed response body.` // // Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. -// Basically you have taken over the control of response parsing from `Resty`. +// You have taken over the control of response parsing from Resty. func (r *Response) RawBody() io.ReadCloser { if r.RawResponse == nil { return nil @@ -142,10 +163,6 @@ func (r *Response) IsError() bool { return r.StatusCode() > 399 } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response Unexported methods -//_______________________________________________________________________ - func (r *Response) setReceivedAt() { r.receivedAt = time.Now() if r.Request.clientTrace != nil { @@ -154,7 +171,10 @@ func (r *Response) setReceivedAt() { } func (r *Response) fmtBodyString(sl int64) string { - if r.body != nil { + if r.Request.client.notParseResponse || r.Request.notParseResponse { + return "***** DO NOT PARSE RESPONSE - Enabled *****" + } + if len(r.body) > 0 { if int64(len(r.body)) > sl { return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body)) } diff --git a/vendor/github.com/go-resty/resty/v2/resty.go b/vendor/github.com/go-resty/resty/v2/resty.go index 6f9c8b4cd7..8428f9b187 100644 --- a/vendor/github.com/go-resty/resty/v2/resty.go +++ b/vendor/github.com/go-resty/resty/v2/resty.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,7 +14,7 @@ import ( ) // Version # of resty -const Version = "2.7.0" +const Version = "2.17.1" // New method creates a new Resty client. func New() *Client { @@ -24,12 +24,12 @@ func New() *Client { }) } -// NewWithClient method creates a new Resty client with given `http.Client`. +// NewWithClient method creates a new Resty client with given [http.Client]. func NewWithClient(hc *http.Client) *Client { return createClient(hc) } -// NewWithLocalAddr method creates a new Resty client with given Local Address +// NewWithLocalAddr method creates a new Resty client with the given Local Address. // to dial from. func NewWithLocalAddr(localAddr net.Addr) *Client { cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) diff --git a/vendor/github.com/go-resty/resty/v2/retry.go b/vendor/github.com/go-resty/resty/v2/retry.go index 00b8514a58..f3198a5280 100644 --- a/vendor/github.com/go-resty/resty/v2/retry.go +++ b/vendor/github.com/go-resty/resty/v2/retry.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,6 +6,7 @@ package resty import ( "context" + "io" "math" "math/rand" "sync" @@ -22,7 +23,7 @@ type ( // Option is to create convenient retry options like wait time, max retries, etc. Option func(*Options) - // RetryConditionFunc type is for retry condition function + // RetryConditionFunc type is for the retry condition function // input: non-nil Response OR request execution error RetryConditionFunc func(*Response, error) bool @@ -32,8 +33,8 @@ type ( // RetryAfterFunc returns time to wait before retry // For example, it can parse HTTP Retry-After header // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html - // Non-nil error is returned if it is found that request is not retryable - // (0, nil) is a special result means 'use default algorithm' + // Non-nil error is returned if it is found that the request is not retryable + // (0, nil) is a special result that means 'use default algorithm' RetryAfterFunc func(*Client, *Response) (time.Duration, error) // Options struct is used to hold retry settings. @@ -43,6 +44,7 @@ type ( maxWaitTime time.Duration retryConditions []RetryConditionFunc retryHooks []OnRetryFunc + resetReaders bool } ) @@ -67,7 +69,7 @@ func MaxWaitTime(value time.Duration) Option { } } -// RetryConditions sets the conditions that will be checked for retry. +// RetryConditions sets the conditions that will be checked for retry func RetryConditions(conditions []RetryConditionFunc) Option { return func(o *Options) { o.retryConditions = conditions @@ -81,6 +83,14 @@ func RetryHooks(hooks []OnRetryFunc) Option { } } +// ResetMultipartReaders sets a boolean value which will lead the start being seeked out +// on all multipart file readers if they implement [io.ReadSeeker] +func ResetMultipartReaders(value bool) Option { + return func(o *Options) { + o.resetReaders = value + } +} + // Backoff retries with increasing timeout duration up until X amount of retries // (Default is 3 attempts, Override with option Retries(n)) func Backoff(operation func() (*Response, error), options ...Option) error { @@ -125,6 +135,15 @@ func Backoff(operation func() (*Response, error), options ...Option) error { return err } + if opts.resetReaders { + if err := resetFileReaders(resp.Request.multipartFiles); err != nil { + return err + } + if err := resetFieldReaders(resp.Request.multipartFields); err != nil { + return err + } + } + for _, hook := range opts.retryHooks { hook(resp, err) } @@ -186,13 +205,16 @@ func sleepDuration(resp *Response, min, max time.Duration, attempt int) (time.Du } // Return capped exponential backoff with jitter -// http://www.awsarchitectureblog.com/2015/03/backoff.html +// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ func jitterBackoff(min, max time.Duration, attempt int) time.Duration { base := float64(min) capLevel := float64(max) temp := math.Min(capLevel, base*math.Exp2(float64(attempt))) ri := time.Duration(temp / 2) + if ri == 0 { + ri = time.Nanosecond + } result := randDuration(ri) if result < min { @@ -219,3 +241,27 @@ func newRnd() *rand.Rand { var src = rand.NewSource(seed) return rand.New(src) } + +func resetFileReaders(files []*File) error { + for _, f := range files { + if rs, ok := f.Reader.(io.ReadSeeker); ok { + if _, err := rs.Seek(0, io.SeekStart); err != nil { + return err + } + } + } + + return nil +} + +func resetFieldReaders(fields []*MultipartField) error { + for _, f := range fields { + if rs, ok := f.Reader.(io.ReadSeeker); ok { + if _, err := rs.Seek(0, io.SeekStart); err != nil { + return err + } + } + } + + return nil +} diff --git a/vendor/github.com/go-resty/resty/v2/shellescape/BUILD.bazel b/vendor/github.com/go-resty/resty/v2/shellescape/BUILD.bazel new file mode 100644 index 0000000000..fe829e3970 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/shellescape/BUILD.bazel @@ -0,0 +1,14 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "shellescape", + srcs = ["shellescape.go"], + importpath = "github.com/go-resty/resty/v2/shellescape", + visibility = ["//visibility:public"], +) + +alias( + name = "go_default_library", + actual = ":shellescape", + visibility = ["//visibility:public"], +) diff --git a/vendor/github.com/go-resty/resty/v2/shellescape/shellescape.go b/vendor/github.com/go-resty/resty/v2/shellescape/shellescape.go new file mode 100644 index 0000000000..1e835cb3b7 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/shellescape/shellescape.go @@ -0,0 +1,40 @@ +// Copyright (c) 2015-present Jeevanandam M (jeeva@myjeeva.com) +// 2024 Ahuigo (https://github.com/ahuigo) +// All rights reserved. +// resty source code and usage is governed by a MIT style +// license that can be found in the LICENSE file. + +/* +Package shellescape provides the methods to escape arbitrary +strings for a safe use as command line arguments in the most common +POSIX shells. + +The original Python package which this work was inspired by can be found +at https://pypi.python.org/pypi/shellescape. +*/ +package shellescape + +import ( + "regexp" + "strings" +) + +var pattern *regexp.Regexp + +func init() { + pattern = regexp.MustCompile(`[^\w@%+=:,./-]`) +} + +// Quote method returns a shell-escaped version of the string. The returned value +// can safely be used as one token in a shell command line. +func Quote(s string) string { + if len(s) == 0 { + return "''" + } + + if pattern.MatchString(s) { + return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" + } + + return s +} diff --git a/vendor/github.com/go-resty/resty/v2/trace.go b/vendor/github.com/go-resty/resty/v2/trace.go index 23cf70335e..9103878564 100644 --- a/vendor/github.com/go-resty/resty/v2/trace.go +++ b/vendor/github.com/go-resty/resty/v2/trace.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -9,6 +9,7 @@ import ( "crypto/tls" "net" "net/http/httptrace" + "sync" "time" ) @@ -16,32 +17,30 @@ import ( // TraceInfo struct //_______________________________________________________________________ -// TraceInfo struct is used provide request trace info such as DNS lookup +// TraceInfo struct is used to provide request trace info such as DNS lookup // duration, Connection obtain duration, Server processing duration, etc. -// -// Since v2.0.0 type TraceInfo struct { - // DNSLookup is a duration that transport took to perform + // DNSLookup is the duration that transport took to perform // DNS lookup. DNSLookup time.Duration - // ConnTime is a duration that took to obtain a successful connection. + // ConnTime is the duration it took to obtain a successful connection. ConnTime time.Duration - // TCPConnTime is a duration that took to obtain the TCP connection. + // TCPConnTime is the duration it took to obtain the TCP connection. TCPConnTime time.Duration - // TLSHandshake is a duration that TLS handshake took place. + // TLSHandshake is the duration of the TLS handshake. TLSHandshake time.Duration - // ServerTime is a duration that server took to respond first byte. + // ServerTime is the server's duration for responding to the first byte. ServerTime time.Duration - // ResponseTime is a duration since first response byte from server to + // ResponseTime is the duration since the first response byte from the server to // request completion. ResponseTime time.Duration - // TotalTime is a duration that total request took end-to-end. + // TotalTime is the duration of the total time request taken end-to-end. TotalTime time.Duration // IsConnReused is whether this connection has been previously @@ -52,7 +51,7 @@ type TraceInfo struct { // idle pool. IsConnWasIdle bool - // ConnIdleTime is a duration how long the connection was previously + // ConnIdleTime is the duration how long the connection that was previously // idle, if IsConnWasIdle is true. ConnIdleTime time.Duration @@ -68,10 +67,11 @@ type TraceInfo struct { // ClientTrace struct and its methods //_______________________________________________________________________ -// tracer struct maps the `httptrace.ClientTrace` hooks into Fields -// with same naming for easy understanding. Plus additional insights -// Request. +// clientTrace struct maps the [httptrace.ClientTrace] hooks into Fields +// with the same naming for easy understanding. Plus additional insights +// [Request]. type clientTrace struct { + lock sync.RWMutex getConn time.Time dnsStart time.Time dnsDone time.Time @@ -84,46 +84,60 @@ type clientTrace struct { gotConnInfo httptrace.GotConnInfo } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Trace unexported methods -//_______________________________________________________________________ - func (t *clientTrace) createContext(ctx context.Context) context.Context { return httptrace.WithClientTrace( ctx, &httptrace.ClientTrace{ DNSStart: func(_ httptrace.DNSStartInfo) { + t.lock.Lock() t.dnsStart = time.Now() + t.lock.Unlock() }, DNSDone: func(_ httptrace.DNSDoneInfo) { + t.lock.Lock() t.dnsDone = time.Now() + t.lock.Unlock() }, ConnectStart: func(_, _ string) { + t.lock.Lock() if t.dnsDone.IsZero() { t.dnsDone = time.Now() } if t.dnsStart.IsZero() { t.dnsStart = t.dnsDone } + t.lock.Unlock() }, ConnectDone: func(net, addr string, err error) { + t.lock.Lock() t.connectDone = time.Now() + t.lock.Unlock() }, GetConn: func(_ string) { + t.lock.Lock() t.getConn = time.Now() + t.lock.Unlock() }, GotConn: func(ci httptrace.GotConnInfo) { + t.lock.Lock() t.gotConn = time.Now() t.gotConnInfo = ci + t.lock.Unlock() }, GotFirstResponseByte: func() { + t.lock.Lock() t.gotFirstResponseByte = time.Now() + t.lock.Unlock() }, TLSHandshakeStart: func() { + t.lock.Lock() t.tlsHandshakeStart = time.Now() + t.lock.Unlock() }, TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { + t.lock.Lock() t.tlsHandshakeDone = time.Now() + t.lock.Unlock() }, }, ) diff --git a/vendor/github.com/go-resty/resty/v2/transport.go b/vendor/github.com/go-resty/resty/v2/transport.go index e15b48c551..13c3de343b 100644 --- a/vendor/github.com/go-resty/resty/v2/transport.go +++ b/vendor/github.com/go-resty/resty/v2/transport.go @@ -1,6 +1,7 @@ +//go:build go1.13 // +build go1.13 -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -24,7 +25,7 @@ func createTransport(localAddr net.Addr) *http.Transport { } return &http.Transport{ Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, + DialContext: transportDialContext(dialer), ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, diff --git a/vendor/github.com/go-resty/resty/v2/transport112.go b/vendor/github.com/go-resty/resty/v2/transport112.go index fbbbc59112..beb0301a2a 100644 --- a/vendor/github.com/go-resty/resty/v2/transport112.go +++ b/vendor/github.com/go-resty/resty/v2/transport112.go @@ -1,6 +1,7 @@ +//go:build !go1.13 // +build !go1.13 -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/go-resty/resty/v2/transport_js.go b/vendor/github.com/go-resty/resty/v2/transport_js.go new file mode 100644 index 0000000000..6227aa9ca2 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/transport_js.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm +// +build js,wasm + +package resty + +import ( + "context" + "net" +) + +func transportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return nil +} diff --git a/vendor/github.com/go-resty/resty/v2/transport_other.go b/vendor/github.com/go-resty/resty/v2/transport_other.go new file mode 100644 index 0000000000..73553c36f7 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/transport_other.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !(js && wasm) +// +build !js !wasm + +package resty + +import ( + "context" + "net" +) + +func transportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return dialer.DialContext +} diff --git a/vendor/github.com/go-resty/resty/v2/util.go b/vendor/github.com/go-resty/resty/v2/util.go index 1d563befdb..0ac470e438 100644 --- a/vendor/github.com/go-resty/resty/v2/util.go +++ b/vendor/github.com/go-resty/resty/v2/util.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,6 +6,7 @@ package resty import ( "bytes" + "errors" "fmt" "io" "log" @@ -18,7 +19,6 @@ import ( "runtime" "sort" "strings" - "sync" ) //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ @@ -64,6 +64,16 @@ func (l *logger) output(format string, v ...interface{}) { l.l.Printf(format, v...) } +//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ +// Rate Limiter interface +//_______________________________________________________________________ + +type RateLimiter interface { + Allow() bool +} + +var ErrRateLimitExceeded = errors.New("rate limit exceeded") + //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ // Package Helper methods //_______________________________________________________________________ @@ -134,10 +144,6 @@ type ResponseLog struct { Body string } -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//_______________________________________________________________________ - // way to disable the HTML escape as opt-in func jsonMarshal(c *Client, r *Request, d interface{}) (*bytes.Buffer, error) { if !r.jsonEscapeHTML || !c.jsonEscapeHTML { @@ -205,7 +211,7 @@ func writeMultipartFormFile(w *multipart.Writer, fieldName, fileName string, r i return err } - partWriter, err := w.CreatePart(createMultipartHeader(fieldName, fileName, http.DetectContentType(cbuf))) + partWriter, err := w.CreatePart(createMultipartHeader(fieldName, fileName, http.DetectContentType(cbuf[:size]))) if err != nil { return err } @@ -279,7 +285,13 @@ func functionName(i interface{}) string { } func acquireBuffer() *bytes.Buffer { - return bufPool.Get().(*bytes.Buffer) + buf := bufPool.Get().(*bytes.Buffer) + if buf.Len() == 0 { + buf.Reset() + return buf + } + bufPool.Put(buf) + return new(bytes.Buffer) } func releaseBuffer(buf *bytes.Buffer) { @@ -289,34 +301,12 @@ func releaseBuffer(buf *bytes.Buffer) { } } -// requestBodyReleaser wraps requests's body and implements custom Close for it. -// The Close method closes original body and releases request body back to sync.Pool. -type requestBodyReleaser struct { - releaseOnce sync.Once - reqBuf *bytes.Buffer - io.ReadCloser -} - -func newRequestBodyReleaser(respBody io.ReadCloser, reqBuf *bytes.Buffer) io.ReadCloser { - if reqBuf == nil { - return respBody - } - - return &requestBodyReleaser{ - reqBuf: reqBuf, - ReadCloser: respBody, +func backToBufPool(buf *bytes.Buffer) { + if buf != nil { + bufPool.Put(buf) } } -func (rr *requestBodyReleaser) Close() error { - err := rr.ReadCloser.Close() - rr.releaseOnce.Do(func() { - releaseBuffer(rr.reqBuf) - }) - - return err -} - func closeq(v interface{}) { if c, ok := v.(io.Closer); ok { silently(c.Close()) @@ -328,25 +318,7 @@ func silently(_ ...interface{}) {} func composeHeaders(c *Client, r *Request, hdrs http.Header) string { str := make([]string, 0, len(hdrs)) for _, k := range sortHeaderKeys(hdrs) { - var v string - if k == "Cookie" { - cv := strings.TrimSpace(strings.Join(hdrs[k], ", ")) - if c.GetClient().Jar != nil { - for _, c := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { - if cv != "" { - cv = cv + "; " + c.String() - } else { - cv = c.String() - } - } - } - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, cv)) - } else { - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", "))) - } - if v != "" { - str = append(str, "\t"+v) - } + str = append(str, "\t"+strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", ")))) } return strings.Join(str, "\n") } @@ -368,6 +340,32 @@ func copyHeaders(hdrs http.Header) http.Header { return nh } +func wrapErrors(n error, inner error) error { + if inner == nil { + return n + } + if n == nil { + return inner + } + return &restyError{ + err: n, + inner: inner, + } +} + +type restyError struct { + err error + inner error +} + +func (e *restyError) Error() string { + return e.err.Error() +} + +func (e *restyError) Unwrap() error { + return e.inner +} + type noRetryErr struct { err error } diff --git a/vendor/github.com/go-resty/resty/v2/util_curl.go b/vendor/github.com/go-resty/resty/v2/util_curl.go new file mode 100644 index 0000000000..073d0492f8 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/util_curl.go @@ -0,0 +1,78 @@ +package resty + +import ( + "bytes" + "io" + "net/http" + "net/http/cookiejar" + + "net/url" + "strings" + + "github.com/go-resty/resty/v2/shellescape" +) + +func buildCurlRequest(req *http.Request, httpCookiejar http.CookieJar) (curl string) { + // 1. Generate curl raw headers + + curl = "curl -X " + req.Method + " " + // req.Host + req.URL.Path + "?" + req.URL.RawQuery + " " + req.Proto + " " + headers := dumpCurlHeaders(req) + for _, kv := range *headers { + curl += `-H ` + shellescape.Quote(kv[0]+": "+kv[1]) + ` ` + } + + // 2. Generate curl cookies + // TODO validate this block of code, I think its not required since cookie captured via Headers + if cookieJar, ok := httpCookiejar.(*cookiejar.Jar); ok { + cookies := cookieJar.Cookies(req.URL) + if len(cookies) > 0 { + curl += `-H ` + shellescape.Quote(dumpCurlCookies(cookies)) + " " + } + } + + // 3. Generate curl body + if req.Body != nil { + buf, _ := io.ReadAll(req.Body) + req.Body = io.NopCloser(bytes.NewBuffer(buf)) // important!! + curl += `-d ` + shellescape.Quote(string(buf)) + " " + } + + urlString := shellescape.Quote(req.URL.String()) + if urlString == "''" { + urlString = "'http://unexecuted-request'" + } + curl += urlString + return curl +} + +// dumpCurlCookies dumps cookies to curl format +func dumpCurlCookies(cookies []*http.Cookie) string { + sb := strings.Builder{} + sb.WriteString("Cookie: ") + for _, cookie := range cookies { + sb.WriteString(cookie.Name + "=" + url.QueryEscape(cookie.Value) + "&") + } + return strings.TrimRight(sb.String(), "&") +} + +// dumpCurlHeaders dumps headers to curl format +func dumpCurlHeaders(req *http.Request) *[][2]string { + headers := [][2]string{} + for k, vs := range req.Header { + for _, v := range vs { + headers = append(headers, [2]string{k, v}) + } + } + n := len(headers) + for i := 0; i < n; i++ { + for j := n - 1; j > i; j-- { + jj := j - 1 + h1, h2 := headers[j], headers[jj] + if h1[0] < h2[0] { + headers[jj], headers[j] = headers[j], headers[jj] + } + } + } + return &headers +} diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go index 6c18ea230b..ea5ae629fd 100644 --- a/vendor/golang.org/x/net/http2/http2.go +++ b/vendor/golang.org/x/net/http2/http2.go @@ -11,8 +11,6 @@ // requires Go 1.6 or later) // // See https://http2.github.io/ for more information on HTTP/2. -// -// See https://http2.golang.org/ for a test server running this code. package http2 // import "golang.org/x/net/http2" import ( diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 6ab02b6c31..d1c8b2640e 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -349,6 +349,9 @@ struct ltchars { #define _HIDIOCGRAWPHYS HIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN) #define _HIDIOCGRAWUNIQ HIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN) +// Renamed in v6.16, commit c6d732c38f93 ("net: ethtool: remove duplicate defines for family info") +#define ETHTOOL_FAMILY_NAME ETHTOOL_GENL_NAME +#define ETHTOOL_FAMILY_VERSION ETHTOOL_GENL_VERSION ' includes_NetBSD=' diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 798f61ad3b..7838ca5db2 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -602,14 +602,9 @@ func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocI return } -// sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) const minIovec = 8 func Readv(fd int, iovs [][]byte) (n int, err error) { - if !darwinKernelVersionMin(11, 0, 0) { - return 0, ENOSYS - } - iovecs := make([]Iovec, 0, minIovec) iovecs = appendBytes(iovecs, iovs) n, err = readv(fd, iovecs) @@ -618,9 +613,6 @@ func Readv(fd int, iovs [][]byte) (n int, err error) { } func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) { - if !darwinKernelVersionMin(11, 0, 0) { - return 0, ENOSYS - } iovecs := make([]Iovec, 0, minIovec) iovecs = appendBytes(iovecs, iovs) n, err = preadv(fd, iovecs, offset) @@ -629,10 +621,6 @@ func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) { } func Writev(fd int, iovs [][]byte) (n int, err error) { - if !darwinKernelVersionMin(11, 0, 0) { - return 0, ENOSYS - } - iovecs := make([]Iovec, 0, minIovec) iovecs = appendBytes(iovecs, iovs) if raceenabled { @@ -644,10 +632,6 @@ func Writev(fd int, iovs [][]byte) (n int, err error) { } func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) { - if !darwinKernelVersionMin(11, 0, 0) { - return 0, ENOSYS - } - iovecs := make([]Iovec, 0, minIovec) iovecs = appendBytes(iovecs, iovs) if raceenabled { @@ -707,45 +691,7 @@ func readvRacedetect(iovecs []Iovec, n int, err error) { } } -func darwinMajorMinPatch() (maj, min, patch int, err error) { - var un Utsname - err = Uname(&un) - if err != nil { - return - } - - var mmp [3]int - c := 0 -Loop: - for _, b := range un.Release[:] { - switch { - case b >= '0' && b <= '9': - mmp[c] = 10*mmp[c] + int(b-'0') - case b == '.': - c++ - if c > 2 { - return 0, 0, 0, ENOTSUP - } - case b == 0: - break Loop - default: - return 0, 0, 0, ENOTSUP - } - } - if c != 2 { - return 0, 0, 0, ENOTSUP - } - return mmp[0], mmp[1], mmp[2], nil -} - -func darwinKernelVersionMin(maj, min, patch int) bool { - actualMaj, actualMin, actualPatch, err := darwinMajorMinPatch() - if err != nil { - return false - } - return actualMaj > maj || actualMaj == maj && (actualMin > min || actualMin == min && actualPatch >= patch) -} - +//sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 9e7a6c5a4f..b6db27d937 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -328,6 +328,8 @@ const ( AUDIT_KERNEL = 0x7d0 AUDIT_KERNEL_OTHER = 0x524 AUDIT_KERN_MODULE = 0x532 + AUDIT_LANDLOCK_ACCESS = 0x58f + AUDIT_LANDLOCK_DOMAIN = 0x590 AUDIT_LAST_FEATURE = 0x1 AUDIT_LAST_KERN_ANOM_MSG = 0x707 AUDIT_LAST_USER_MSG = 0x4af @@ -492,6 +494,7 @@ const ( BPF_F_BEFORE = 0x8 BPF_F_ID = 0x20 BPF_F_NETFILTER_IP_DEFRAG = 0x1 + BPF_F_PREORDER = 0x40 BPF_F_QUERY_EFFECTIVE = 0x1 BPF_F_REDIRECT_FLAGS = 0x19 BPF_F_REPLACE = 0x4 @@ -528,6 +531,7 @@ const ( BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 + BPF_LOAD_ACQ = 0x100 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 @@ -555,6 +559,7 @@ const ( BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 + BPF_STORE_REL = 0x110 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAG_SIZE = 0x8 @@ -844,9 +849,9 @@ const ( DM_UUID_FLAG = 0x4000 DM_UUID_LEN = 0x81 DM_VERSION = 0xc138fd00 - DM_VERSION_EXTRA = "-ioctl (2025-01-17)" + DM_VERSION_EXTRA = "-ioctl (2025-04-28)" DM_VERSION_MAJOR = 0x4 - DM_VERSION_MINOR = 0x31 + DM_VERSION_MINOR = 0x32 DM_VERSION_PATCHLEVEL = 0x0 DT_BLK = 0x6 DT_CHR = 0x2 @@ -937,9 +942,6 @@ const ( EPOLL_CTL_MOD = 0x3 EPOLL_IOC_TYPE = 0x8a EROFS_SUPER_MAGIC_V1 = 0xe0f5e1e2 - ESP_V4_FLOW = 0xa - ESP_V6_FLOW = 0xc - ETHER_FLOW = 0x12 ETHTOOL_BUSINFO_LEN = 0x20 ETHTOOL_EROMVERS_LEN = 0x20 ETHTOOL_FAMILY_NAME = "ethtool" @@ -1213,6 +1215,7 @@ const ( FAN_EVENT_INFO_TYPE_DFID_NAME = 0x2 FAN_EVENT_INFO_TYPE_ERROR = 0x5 FAN_EVENT_INFO_TYPE_FID = 0x1 + FAN_EVENT_INFO_TYPE_MNT = 0x7 FAN_EVENT_INFO_TYPE_NEW_DFID_NAME = 0xc FAN_EVENT_INFO_TYPE_OLD_DFID_NAME = 0xa FAN_EVENT_INFO_TYPE_PIDFD = 0x4 @@ -1231,9 +1234,12 @@ const ( FAN_MARK_IGNORED_SURV_MODIFY = 0x40 FAN_MARK_IGNORE_SURV = 0x440 FAN_MARK_INODE = 0x0 + FAN_MARK_MNTNS = 0x110 FAN_MARK_MOUNT = 0x10 FAN_MARK_ONLYDIR = 0x8 FAN_MARK_REMOVE = 0x2 + FAN_MNT_ATTACH = 0x1000000 + FAN_MNT_DETACH = 0x2000000 FAN_MODIFY = 0x2 FAN_MOVE = 0xc0 FAN_MOVED_FROM = 0x40 @@ -1255,6 +1261,7 @@ const ( FAN_REPORT_DIR_FID = 0x400 FAN_REPORT_FD_ERROR = 0x2000 FAN_REPORT_FID = 0x200 + FAN_REPORT_MNT = 0x4000 FAN_REPORT_NAME = 0x800 FAN_REPORT_PIDFD = 0x80 FAN_REPORT_TARGET_FID = 0x1000 @@ -1274,6 +1281,7 @@ const ( FIB_RULE_PERMANENT = 0x1 FIB_RULE_UNRESOLVED = 0x4 FIDEDUPERANGE = 0xc0189436 + FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED = 0x1 FSCRYPT_KEY_DESCRIPTOR_SIZE = 0x8 FSCRYPT_KEY_DESC_PREFIX = "fscrypt:" FSCRYPT_KEY_DESC_PREFIX_SIZE = 0x8 @@ -1582,7 +1590,6 @@ const ( IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b - IPV6_FLOW = 0x11 IPV6_FREEBIND = 0x4e IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 @@ -1633,7 +1640,6 @@ const ( IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c - IPV6_USER_FLOW = 0xe IPV6_V6ONLY = 0x1a IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 @@ -1695,7 +1701,6 @@ const ( IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 - IP_USER_FLOW = 0xd IP_XFRM_POLICY = 0x11 ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 @@ -1817,7 +1822,11 @@ const ( LANDLOCK_ACCESS_FS_WRITE_FILE = 0x2 LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 + LANDLOCK_CREATE_RULESET_ERRATA = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 + LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON = 0x2 + LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF = 0x1 + LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF = 0x4 LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET = 0x1 LANDLOCK_SCOPE_SIGNAL = 0x2 LINUX_REBOOT_CMD_CAD_OFF = 0x0 @@ -2493,6 +2502,10 @@ const ( PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 + PR_FUTEX_HASH = 0x4e + PR_FUTEX_HASH_GET_IMMUTABLE = 0x3 + PR_FUTEX_HASH_GET_SLOTS = 0x2 + PR_FUTEX_HASH_SET_SLOTS = 0x1 PR_GET_AUXV = 0x41555856 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 @@ -2652,6 +2665,10 @@ const ( PR_TAGGED_ADDR_ENABLE = 0x1 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 + PR_TIMER_CREATE_RESTORE_IDS = 0x4d + PR_TIMER_CREATE_RESTORE_IDS_GET = 0x2 + PR_TIMER_CREATE_RESTORE_IDS_OFF = 0x0 + PR_TIMER_CREATE_RESTORE_IDS_ON = 0x1 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 @@ -2732,6 +2749,7 @@ const ( PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b + PTRACE_SET_SYSCALL_INFO = 0x4212 PTRACE_SET_SYSCALL_USER_DISPATCH_CONFIG = 0x4210 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 @@ -2982,6 +3000,7 @@ const ( RTPROT_NTK = 0xf RTPROT_OPENR = 0x63 RTPROT_OSPF = 0xbc + RTPROT_OVN = 0x54 RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_RIP = 0xbd @@ -3336,7 +3355,7 @@ const ( TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 - TASKSTATS_VERSION = 0xf + TASKSTATS_VERSION = 0x10 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 @@ -3406,8 +3425,6 @@ const ( TCP_TX_DELAY = 0x25 TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 - TCP_V4_FLOW = 0x1 - TCP_V6_FLOW = 0x5 TCP_WINDOW_CLAMP = 0xa TCP_ZEROCOPY_RECEIVE = 0x23 TFD_TIMER_ABSTIME = 0x1 @@ -3530,8 +3547,6 @@ const ( UDP_NO_CHECK6_RX = 0x66 UDP_NO_CHECK6_TX = 0x65 UDP_SEGMENT = 0x67 - UDP_V4_FLOW = 0x2 - UDP_V6_FLOW = 0x6 UMOUNT_NOFOLLOW = 0x8 USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff @@ -3574,7 +3589,7 @@ const ( WDIOS_TEMPPANIC = 0x4 WDIOS_UNKNOWN = -0x1 WEXITED = 0x4 - WGALLOWEDIP_A_MAX = 0x3 + WGALLOWEDIP_A_MAX = 0x4 WGDEVICE_A_MAX = 0x8 WGPEER_A_MAX = 0xa WG_CMD_MAX = 0x1 @@ -3688,6 +3703,7 @@ const ( XDP_SHARED_UMEM = 0x1 XDP_STATISTICS = 0x7 XDP_TXMD_FLAGS_CHECKSUM = 0x2 + XDP_TXMD_FLAGS_LAUNCH_TIME = 0x4 XDP_TXMD_FLAGS_TIMESTAMP = 0x1 XDP_TX_METADATA = 0x2 XDP_TX_RING = 0x3 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index a8c421e29b..1c37f9fbc4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -360,6 +361,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 9a88d18130..6f54d34aef 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -361,6 +362,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 7cb6a867ef..783ec5c126 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -366,6 +367,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index d0ecd2c583..ca83d3ba16 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -359,6 +360,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index 7a2940ae0a..607e611c0c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -353,6 +354,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index d14ca8f2ec..b9cb5bd3c0 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x200 @@ -359,6 +360,7 @@ const ( SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 2da1bac1e3..65b078a638 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x200 @@ -359,6 +360,7 @@ const ( SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 28727514b5..5298a3033d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x200 @@ -359,6 +360,7 @@ const ( SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 7f287b54b5..7bc557c876 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x200 @@ -359,6 +360,7 @@ const ( SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 7e5f9e6aa8..152399bb04 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -68,6 +68,7 @@ const ( CS8 = 0x300 CSIZE = 0x300 CSTOPB = 0x400 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x40 @@ -414,6 +415,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 37c87952fc..1a1ce2409c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x300 CSIZE = 0x300 CSTOPB = 0x400 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x40 @@ -418,6 +419,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 5220133613..4231a1fb57 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -68,6 +68,7 @@ const ( CS8 = 0x300 CSIZE = 0x300 CSTOPB = 0x400 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x40 @@ -418,6 +419,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 4bfe2b5b6e..21c0e95266 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -350,6 +351,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index e3cffb869a..f00d1cd7cf 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -68,6 +68,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0xfd12 ECCGETLAYOUT = 0x81484d11 ECCGETSTATS = 0x80104d12 ECHOCTL = 0x200 @@ -422,6 +423,7 @@ const ( SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSPIDFD = 0x4c + SO_PASSRIGHTS = 0x53 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index c219c8db39..bc8d539e6a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -71,6 +71,7 @@ const ( CS8 = 0x30 CSIZE = 0x30 CSTOPB = 0x40 + DM_MPATH_PROBE_PATHS = 0x2000fd12 ECCGETLAYOUT = 0x41484d11 ECCGETSTATS = 0x40104d12 ECHOCTL = 0x200 @@ -461,6 +462,7 @@ const ( SO_OOBINLINE = 0x100 SO_PASSCRED = 0x2 SO_PASSPIDFD = 0x55 + SO_PASSRIGHTS = 0x5c SO_PASSSEC = 0x1f SO_PEEK_OFF = 0x26 SO_PEERCRED = 0x40 diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index c79aaff306..aca56ee494 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -462,4 +462,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index 5eb450695e..2ea1ef58c3 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -385,4 +385,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 05e5029744..d22c8af319 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -426,4 +426,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index 38c53ec51b..5ee264ae97 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -329,4 +329,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go index 31d2e71a18..f9f03ebf5f 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go @@ -325,4 +325,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index f4184a336b..87c2118e84 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -446,4 +446,5 @@ const ( SYS_GETXATTRAT = 4464 SYS_LISTXATTRAT = 4465 SYS_REMOVEXATTRAT = 4466 + SYS_OPEN_TREE_ATTR = 4467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index 05b9962278..391ad102fb 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -376,4 +376,5 @@ const ( SYS_GETXATTRAT = 5464 SYS_LISTXATTRAT = 5465 SYS_REMOVEXATTRAT = 5466 + SYS_OPEN_TREE_ATTR = 5467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index 43a256e9e6..5656157757 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -376,4 +376,5 @@ const ( SYS_GETXATTRAT = 5464 SYS_LISTXATTRAT = 5465 SYS_REMOVEXATTRAT = 5466 + SYS_OPEN_TREE_ATTR = 5467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index eea5ddfc22..0482b52e3c 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -446,4 +446,5 @@ const ( SYS_GETXATTRAT = 4464 SYS_LISTXATTRAT = 4465 SYS_REMOVEXATTRAT = 4466 + SYS_OPEN_TREE_ATTR = 4467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go index 0d777bfbb1..71806f08f3 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go @@ -453,4 +453,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index b446365025..e35a710582 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -425,4 +425,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index 0c7d21c188..2aea476705 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -425,4 +425,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 8405391698..6c9bb4e560 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -330,4 +330,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index fcf1b790d6..680bc9915a 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -391,4 +391,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index 52d15b5f9d..620f271052 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -404,4 +404,5 @@ const ( SYS_GETXATTRAT = 464 SYS_LISTXATTRAT = 465 SYS_REMOVEXATTRAT = 466 + SYS_OPEN_TREE_ATTR = 467 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 8bcac2835f..cd236443f6 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -115,7 +115,9 @@ type Statx_t struct { Atomic_write_unit_max uint32 Atomic_write_segments_max uint32 Dio_read_offset_align uint32 - _ [9]uint64 + Atomic_write_unit_max_opt uint32 + _ [1]uint32 + _ [8]uint64 } type Fsid struct { @@ -199,7 +201,8 @@ type FscryptAddKeyArg struct { Key_spec FscryptKeySpecifier Raw_size uint32 Key_id uint32 - _ [8]uint32 + Flags uint32 + _ [7]uint32 } type FscryptRemoveKeyArg struct { @@ -2317,6 +2320,11 @@ const ( NFT_CT_AVGPKT = 0x10 NFT_CT_ZONE = 0x11 NFT_CT_EVENTMASK = 0x12 + NFT_CT_SRC_IP = 0x13 + NFT_CT_DST_IP = 0x14 + NFT_CT_SRC_IP6 = 0x15 + NFT_CT_DST_IP6 = 0x16 + NFT_CT_ID = 0x17 NFTA_CT_UNSPEC = 0x0 NFTA_CT_DREG = 0x1 NFTA_CT_KEY = 0x2 @@ -2597,8 +2605,8 @@ const ( SOF_TIMESTAMPING_BIND_PHC = 0x8000 SOF_TIMESTAMPING_OPT_ID_TCP = 0x10000 - SOF_TIMESTAMPING_LAST = 0x20000 - SOF_TIMESTAMPING_MASK = 0x3ffff + SOF_TIMESTAMPING_LAST = 0x40000 + SOF_TIMESTAMPING_MASK = 0x7ffff SCM_TSTAMP_SND = 0x0 SCM_TSTAMP_SCHED = 0x1 @@ -4044,7 +4052,7 @@ const ( ETHTOOL_A_TSINFO_PHC_INDEX = 0x5 ETHTOOL_A_TSINFO_STATS = 0x6 ETHTOOL_A_TSINFO_HWTSTAMP_PROVIDER = 0x7 - ETHTOOL_A_TSINFO_MAX = 0x7 + ETHTOOL_A_TSINFO_MAX = 0x9 ETHTOOL_A_CABLE_TEST_UNSPEC = 0x0 ETHTOOL_A_CABLE_TEST_HEADER = 0x1 ETHTOOL_A_CABLE_TEST_MAX = 0x1 @@ -4130,6 +4138,19 @@ const ( ETHTOOL_A_TUNNEL_INFO_MAX = 0x2 ) +const ( + TCP_V4_FLOW = 0x1 + UDP_V4_FLOW = 0x2 + TCP_V6_FLOW = 0x5 + UDP_V6_FLOW = 0x6 + ESP_V4_FLOW = 0xa + ESP_V6_FLOW = 0xc + IP_USER_FLOW = 0xd + IPV6_USER_FLOW = 0xe + IPV6_FLOW = 0x11 + ETHER_FLOW = 0x12 +) + const SPEED_UNKNOWN = -0x1 type EthtoolDrvinfo struct { @@ -4780,7 +4801,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x150 + NL80211_ATTR_MAX = 0x151 NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS = 0x143 @@ -5414,7 +5435,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x21 + NL80211_FREQUENCY_ATTR_MAX = 0x22 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc @@ -5530,7 +5551,7 @@ const ( NL80211_MAX_SUPP_SELECTORS = 0x80 NL80211_MBSSID_CONFIG_ATTR_EMA = 0x5 NL80211_MBSSID_CONFIG_ATTR_INDEX = 0x3 - NL80211_MBSSID_CONFIG_ATTR_MAX = 0x5 + NL80211_MBSSID_CONFIG_ATTR_MAX = 0x6 NL80211_MBSSID_CONFIG_ATTR_MAX_EMA_PROFILE_PERIODICITY = 0x2 NL80211_MBSSID_CONFIG_ATTR_MAX_INTERFACES = 0x1 NL80211_MBSSID_CONFIG_ATTR_TX_IFINDEX = 0x4 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index 62db85f6cb..485f2d3a1b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -282,19 +282,13 @@ type Taskstats struct { Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - _ [4]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -330,17 +324,11 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 _ [4]byte Ac_tgetime uint64 @@ -348,10 +336,22 @@ type Taskstats struct { Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index 7d89d648d9..ecbd1ad8bc 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -300,16 +300,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -344,27 +338,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 9c0b39eec7..02f0463a44 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -91,7 +91,7 @@ type Stat_t struct { Gid uint32 Rdev uint64 _ uint16 - _ [4]byte + _ [6]byte Size int64 Blksize int32 _ [4]byte @@ -273,19 +273,13 @@ type Taskstats struct { Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - _ [4]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 @@ -321,17 +315,11 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 _ [4]byte Ac_tgetime uint64 @@ -339,10 +327,22 @@ type Taskstats struct { Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index de9c7ff36c..6f4d400d24 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -279,16 +279,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -323,27 +317,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go index 2336bd2bf0..cd532cfa55 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go @@ -280,16 +280,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -324,27 +318,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 4711f0be16..4133620851 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -278,19 +278,13 @@ type Taskstats struct { Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - _ [4]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -326,17 +320,11 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 _ [4]byte Ac_tgetime uint64 @@ -344,10 +332,22 @@ type Taskstats struct { Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index ab99a34b99..eaa37eb718 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -282,16 +282,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -326,27 +320,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 04c9866e3c..98ae6a1e4a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -282,16 +282,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -326,27 +320,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index 60aa69f618..cae1961594 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -278,19 +278,13 @@ type Taskstats struct { Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - _ [4]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -326,17 +320,11 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 _ [4]byte Ac_tgetime uint64 @@ -344,10 +332,22 @@ type Taskstats struct { Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go index cb4fad785d..6ce3b4e028 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go @@ -90,7 +90,7 @@ type Stat_t struct { Gid uint32 Rdev uint64 _ uint16 - _ [4]byte + _ [6]byte Size int64 Blksize int32 _ [4]byte @@ -285,19 +285,13 @@ type Taskstats struct { Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - _ [4]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 @@ -333,17 +327,11 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 _ [4]byte Ac_tgetime uint64 @@ -351,10 +339,22 @@ type Taskstats struct { Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 60272cfce8..c7429c6a14 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -289,16 +289,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 @@ -333,27 +327,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 3f5b91bc0d..4bf4baf4ca 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -289,16 +289,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 @@ -333,27 +327,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 51550f15a6..e9709d70af 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -307,16 +307,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 @@ -351,27 +345,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index 3239e50e0e..fb44268ca7 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -302,16 +302,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -346,27 +340,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index faf2002783..9c38265c74 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -284,16 +284,10 @@ type Taskstats struct { Ac_nice uint8 Cpu_count uint64 Cpu_delay_total uint64 - Cpu_delay_max uint64 - Cpu_delay_min uint64 Blkio_count uint64 Blkio_delay_total uint64 - Blkio_delay_max uint64 - Blkio_delay_min uint64 Swapin_count uint64 Swapin_delay_total uint64 - Swapin_delay_max uint64 - Swapin_delay_min uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 @@ -328,27 +322,33 @@ type Taskstats struct { Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 - Freepages_delay_max uint64 - Freepages_delay_min uint64 Thrashing_count uint64 Thrashing_delay_total uint64 - Thrashing_delay_max uint64 - Thrashing_delay_min uint64 Ac_btime64 uint64 Compact_count uint64 Compact_delay_total uint64 - Compact_delay_max uint64 - Compact_delay_min uint64 Ac_tgid uint32 Ac_tgetime uint64 Ac_exe_dev uint64 Ac_exe_inode uint64 Wpcopy_count uint64 Wpcopy_delay_total uint64 - Wpcopy_delay_max uint64 - Wpcopy_delay_min uint64 Irq_count uint64 Irq_delay_total uint64 + Cpu_delay_max uint64 + Cpu_delay_min uint64 + Blkio_delay_max uint64 + Blkio_delay_min uint64 + Swapin_delay_max uint64 + Swapin_delay_min uint64 + Freepages_delay_max uint64 + Freepages_delay_min uint64 + Thrashing_delay_max uint64 + Thrashing_delay_min uint64 + Compact_delay_max uint64 + Compact_delay_min uint64 + Wpcopy_delay_max uint64 + Wpcopy_delay_min uint64 Irq_delay_max uint64 Irq_delay_min uint64 } diff --git a/vendor/golang.org/x/term/term_windows.go b/vendor/golang.org/x/term/term_windows.go index df6bf948e1..0ddd81c02a 100644 --- a/vendor/golang.org/x/term/term_windows.go +++ b/vendor/golang.org/x/term/term_windows.go @@ -20,12 +20,14 @@ func isTerminal(fd int) bool { return err == nil } +// This is intended to be used on a console input handle. +// See https://learn.microsoft.com/en-us/windows/console/setconsolemode func makeRaw(fd int) (*State, error) { var st uint32 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { return nil, err } - raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) + raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT) raw |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil { return nil, err diff --git a/vendor/golang.org/x/term/terminal.go b/vendor/golang.org/x/term/terminal.go index 13e9a64ad1..bddb2e2aeb 100644 --- a/vendor/golang.org/x/term/terminal.go +++ b/vendor/golang.org/x/term/terminal.go @@ -146,6 +146,7 @@ const ( keyCtrlD = 4 keyCtrlU = 21 keyEnter = '\r' + keyLF = '\n' keyEscape = 27 keyBackspace = 127 keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota @@ -497,7 +498,7 @@ func (t *Terminal) historyAdd(entry string) { // handleKey processes the given key and, optionally, returns a line of text // that the user has entered. func (t *Terminal) handleKey(key rune) (line string, ok bool) { - if t.pasteActive && key != keyEnter { + if t.pasteActive && key != keyEnter && key != keyLF { t.addKeyToLine(key) return } @@ -567,7 +568,7 @@ func (t *Terminal) handleKey(key rune) (line string, ok bool) { t.setLine(runes, len(runes)) } } - case keyEnter: + case keyEnter, keyLF: t.moveCursorToPos(len(t.line)) t.queue([]rune("\r\n")) line = string(t.line) @@ -812,6 +813,10 @@ func (t *Terminal) readLine() (line string, err error) { if !t.pasteActive { lineIsPasted = false } + // If we have CR, consume LF if present (CRLF sequence) to avoid returning an extra empty line. + if key == keyEnter && len(rest) > 0 && rest[0] == keyLF { + rest = rest[1:] + } line, lineOk = t.handleKey(key) } if len(rest) > 0 { diff --git a/vendor/golang.org/x/time/LICENSE b/vendor/golang.org/x/time/LICENSE index 6a66aea5ea..2a7cf70da6 100644 --- a/vendor/golang.org/x/time/LICENSE +++ b/vendor/golang.org/x/time/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index f0e0cf3cb1..794b2e32bf 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -52,6 +52,8 @@ func Every(interval time.Duration) Limit { // or its associated context.Context is canceled. // // The methods AllowN, ReserveN, and WaitN consume n tokens. +// +// Limiter is safe for simultaneous use by multiple goroutines. type Limiter struct { mu sync.Mutex limit Limit @@ -83,7 +85,7 @@ func (lim *Limiter) Burst() int { // TokensAt returns the number of tokens available at time t. func (lim *Limiter) TokensAt(t time.Time) float64 { lim.mu.Lock() - _, tokens := lim.advance(t) // does not mutate lim + tokens := lim.advance(t) // does not mutate lim lim.mu.Unlock() return tokens } @@ -97,8 +99,9 @@ func (lim *Limiter) Tokens() float64 { // bursts of at most b tokens. func NewLimiter(r Limit, b int) *Limiter { return &Limiter{ - limit: r, - burst: b, + limit: r, + burst: b, + tokens: float64(b), } } @@ -183,7 +186,7 @@ func (r *Reservation) CancelAt(t time.Time) { return } // advance time to now - t, tokens := r.lim.advance(t) + tokens := r.lim.advance(t) // calculate new number of tokens tokens += restoreTokens if burst := float64(r.lim.burst); tokens > burst { @@ -304,7 +307,7 @@ func (lim *Limiter) SetLimitAt(t time.Time, newLimit Limit) { lim.mu.Lock() defer lim.mu.Unlock() - t, tokens := lim.advance(t) + tokens := lim.advance(t) lim.last = t lim.tokens = tokens @@ -321,7 +324,7 @@ func (lim *Limiter) SetBurstAt(t time.Time, newBurst int) { lim.mu.Lock() defer lim.mu.Unlock() - t, tokens := lim.advance(t) + tokens := lim.advance(t) lim.last = t lim.tokens = tokens @@ -342,21 +345,9 @@ func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) tokens: n, timeToAct: t, } - } else if lim.limit == 0 { - var ok bool - if lim.burst >= n { - ok = true - lim.burst -= n - } - return Reservation{ - ok: ok, - lim: lim, - tokens: lim.burst, - timeToAct: t, - } } - t, tokens := lim.advance(t) + tokens := lim.advance(t) // Calculate the remaining number of tokens resulting from the request. tokens -= float64(n) @@ -389,10 +380,11 @@ func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) return r } -// advance calculates and returns an updated state for lim resulting from the passage of time. +// advance calculates and returns an updated number of tokens for lim +// resulting from the passage of time. // lim is not changed. // advance requires that lim.mu is held. -func (lim *Limiter) advance(t time.Time) (newT time.Time, newTokens float64) { +func (lim *Limiter) advance(t time.Time) (newTokens float64) { last := lim.last if t.Before(last) { last = t @@ -405,7 +397,7 @@ func (lim *Limiter) advance(t time.Time) (newT time.Time, newTokens float64) { if burst := float64(lim.burst); tokens > burst { tokens = burst } - return t, tokens + return tokens } // durationFromTokens is a unit conversion function from the number of tokens to the duration @@ -414,8 +406,15 @@ func (limit Limit) durationFromTokens(tokens float64) time.Duration { if limit <= 0 { return InfDuration } - seconds := tokens / float64(limit) - return time.Duration(float64(time.Second) * seconds) + + duration := (tokens / float64(limit)) * float64(time.Second) + + // Cap the duration to the maximum representable int64 value, to avoid overflow. + if duration > float64(math.MaxInt64) { + return InfDuration + } + + return time.Duration(duration) } // tokensFromDuration is a unit conversion function from a time duration to the number of tokens diff --git a/vendor/golang.org/x/time/rate/sometimes.go b/vendor/golang.org/x/time/rate/sometimes.go index 6ba99ddb67..9b83932692 100644 --- a/vendor/golang.org/x/time/rate/sometimes.go +++ b/vendor/golang.org/x/time/rate/sometimes.go @@ -61,7 +61,9 @@ func (s *Sometimes) Do(f func()) { (s.Every > 0 && s.count%s.Every == 0) || (s.Interval > 0 && time.Since(s.last) >= s.Interval) { f() - s.last = time.Now() + if s.Interval > 0 { + s.last = time.Now() + } } s.count++ } diff --git a/vendor/golang.org/x/tools/go/ast/inspector/typeof.go b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go index e936c67c98..be0f990a29 100644 --- a/vendor/golang.org/x/tools/go/ast/inspector/typeof.go +++ b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go @@ -217,7 +217,6 @@ func typeOf(n ast.Node) uint64 { return 0 } -//go:linkname maskOf golang.org/x/tools/go/ast/inspector.maskOf func maskOf(nodes []ast.Node) uint64 { if len(nodes) == 0 { return math.MaxUint64 // match all node types diff --git a/vendor/modules.txt b/vendor/modules.txt index ed4496dfd0..bda9a90013 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -250,9 +250,10 @@ github.com/go-openapi/jsonreference/internal # github.com/go-openapi/swag v0.22.3 ## explicit; go 1.18 github.com/go-openapi/swag -# github.com/go-resty/resty/v2 v2.7.0 -## explicit; go 1.11 +# github.com/go-resty/resty/v2 v2.17.1 +## explicit; go 1.23.0 github.com/go-resty/resty/v2 +github.com/go-resty/resty/v2/shellescape # github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 ## explicit; go 1.13 github.com/go-task/slim-sprig @@ -783,7 +784,7 @@ go.starlark.net/resolve go.starlark.net/starlark go.starlark.net/starlarkstruct go.starlark.net/syntax -# golang.org/x/crypto v0.40.0 +# golang.org/x/crypto v0.41.0 ## explicit; go 1.23.0 golang.org/x/crypto/blowfish golang.org/x/crypto/cast5 @@ -802,7 +803,7 @@ golang.org/x/crypto/ssh golang.org/x/crypto/ssh/agent golang.org/x/crypto/ssh/internal/bcrypt_pbkdf golang.org/x/crypto/ssh/knownhosts -# golang.org/x/net v0.42.0 +# golang.org/x/net v0.43.0 ## explicit; go 1.23.0 golang.org/x/net/context golang.org/x/net/context/ctxhttp @@ -826,17 +827,17 @@ golang.org/x/oauth2/internal # golang.org/x/sync v0.16.0 ## explicit; go 1.23.0 golang.org/x/sync/errgroup -# golang.org/x/sys v0.34.0 +# golang.org/x/sys v0.35.0 ## explicit; go 1.23.0 golang.org/x/sys/cpu golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.33.0 +# golang.org/x/term v0.34.0 ## explicit; go 1.23.0 golang.org/x/term -# golang.org/x/text v0.27.0 +# golang.org/x/text v0.28.0 ## explicit; go 1.23.0 golang.org/x/text/encoding golang.org/x/text/encoding/charmap @@ -859,10 +860,10 @@ golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm golang.org/x/text/width -# golang.org/x/time v0.3.0 -## explicit +# golang.org/x/time v0.12.0 +## explicit; go 1.23.0 golang.org/x/time/rate -# golang.org/x/tools v0.34.0 +# golang.org/x/tools v0.35.0 ## explicit; go 1.23.0 golang.org/x/tools/go/ast/edge golang.org/x/tools/go/ast/inspector