Compare commits
214 Commits
Author | SHA1 | Date | |
---|---|---|---|
fa5602486a | |||
d5690ef2b7 | |||
134031e18b | |||
9743a7f9b1 | |||
2225b95e3e | |||
b76b8d3114 | |||
b92b2541e0 | |||
9d955fc079 | |||
1be75ea264 | |||
d4a07099a2 | |||
a648bf77f4 | |||
0eb663fffe | |||
|
fd803b1fe0 | ||
|
4c2178305d | ||
9149aeb3de | |||
dcadd64941 | |||
8207d4154f | |||
d7524cbe01 | |||
0e7b8e73a8 | |||
35146aa717 | |||
3f44a41d30 | |||
090100e522 | |||
0bf8053d72 | |||
42bdd79b3d | |||
5fa952c86a | |||
|
d861c31a05 | ||
e7dc59157d | |||
|
7f7081e6e8 | ||
d441f151e0 | |||
|
6a6be26ef1 | ||
d1d5e0f4ac | |||
|
3f8976ee62 | ||
2078f2e700 | |||
|
007d45fc7b | ||
6c84752ccd | |||
|
54d21ba6e1 | ||
5b1f1df17a | |||
|
11d7ee54fd | ||
41d606b4e8 | |||
|
5f6f06c239 | ||
|
f80bb95119 | ||
|
cd23f93d57 | ||
f625d5c958 | |||
|
8b068fb7ab | ||
3a1e9ec707 | |||
|
4d6a98782c | ||
af838ec6e5 | |||
|
0c90ea28d9 | ||
90e327726b | |||
|
6e29ac652b | ||
f8b0fe881f | |||
|
2941a335f0 | ||
712ba79b55 | |||
|
3df3d6bfa3 | ||
bed23083cf | |||
|
79175c96aa | ||
|
c23192f2b6 | ||
2bf129d6ab | |||
4bf60486e0 | |||
d048278b84 | |||
|
1cf18ac2a9 | ||
|
251f6f70c4 | ||
|
26bf526741 | ||
|
a86c824eb7 | ||
|
f8cd67b8cd | ||
feb5fec0dd | |||
|
37996fbe90 | ||
08a22e02f9 | |||
|
3358ce8aa2 | ||
|
74158bd60b | ||
930530cbae | |||
|
24a8dbdc4b | ||
c3c580163d | |||
4ad526253a | |||
|
3eca811f81 | ||
|
367fe6d579 | ||
b86a166d08 | |||
|
ecd2711714 | ||
0e82845989 | |||
|
670a31c9ef | ||
6f136a039b | |||
|
c8516877ee | ||
2075368ba3 | |||
|
fbef71bae8 | ||
a946d63cae | |||
|
bc47181f45 | ||
e29671add6 | |||
|
dede9e6488 | ||
2f658787d4 | |||
|
b8ad04a42a | ||
766cbd8ae0 | |||
847352a8d3 | |||
147c2d756e | |||
f42994e5c0 | |||
08b3e7e23e | |||
2f70890e6c | |||
e9be505c59 | |||
13749e7a4d | |||
91cf06abbd | |||
a1f29249d3 | |||
db9c686306 | |||
b74add18c1 | |||
5d3cbfc7d3 | |||
f42e8883ae | |||
93344a3f7b | |||
2e218748e8 | |||
178d68aae9 | |||
2061b2dbb6 | |||
fa9e204032 | |||
bce6f8c3e7 | |||
1ee46a0aac | |||
4f749c5bb1 | |||
8231f4f7f6 | |||
241114aeb1 | |||
e4541d8b44 | |||
b658f5091a | |||
c21d30e4a0 | |||
1349df4d97 | |||
6dfc8b8a01 | |||
d280ea260e | |||
|
e9295b1d12 | ||
|
75b102666f | ||
18b95d7dde | |||
|
6d3d8ccd14 | ||
f37c8fd5d4 | |||
|
c0bfe416b1 | ||
ce520397c4 | |||
|
3cd4e16c36 | ||
3dccbcba98 | |||
|
7572ef631d | ||
030d906f87 | |||
|
bfefab250f | ||
82b7b5e4fb | |||
|
980bea6e4f | ||
a7ce52d564 | |||
|
4771d5e12b | ||
6be01f2cb2 | |||
3829766afd | |||
a2939066a5 | |||
|
e6718f368a | ||
381f3e051e | |||
757c458f60 | |||
a2f089f890 | |||
|
d85e3fdce2 | ||
5f370d1a31 | |||
|
2b47343e07 | ||
00c1d3618f | |||
|
0f80c9f7ba | ||
a275ffa001 | |||
|
2800d4c78b | ||
a609f15425 | |||
|
83cc922771 | ||
2bba395ba3 | |||
a360ef0e8f | |||
5f0e4915f6 | |||
f02efaf18c | |||
279d111d39 | |||
928455a651 | |||
6df77d317d | |||
e8f7fab079 | |||
ae6f29e540 | |||
de6cdb4e4d | |||
0398d969d5 | |||
10419bc74a | |||
93ce60f59c | |||
61c082cb2f | |||
22f1b6551a | |||
73b7d998c0 | |||
4aca8e1ce0 | |||
3592052ac9 | |||
fd5479f6e7 | |||
4fe11b430e | |||
5dc57579c3 | |||
|
f974460ff3 | ||
5c54b82aaf | |||
a5bf3e2edc | |||
3a2bac8723 | |||
|
9a72dba9df | ||
00e853e3ee | |||
5aff0014bb | |||
807b4dc41a | |||
a1f432fac9 | |||
dd7e872858 | |||
57c2a5b95f | |||
73fc3d34f0 | |||
09e7282b2b | |||
5f029fd432 | |||
8555ebdd5c | |||
273da35b92 | |||
556e8dd568 | |||
f3573e651b | |||
8074f9f617 | |||
e497b5fa89 | |||
520dc29f89 | |||
59d6c26003 | |||
fade40754a | |||
f39d449ca2 | |||
7cab3c18a7 | |||
7098c252dc | |||
3cbc879769 | |||
05add422d1 | |||
|
b4970ee807 | ||
|
f4c91686f4 | ||
ee9b7493e3 | |||
|
0182d6ab56 | ||
d99e97090c | |||
8de7912a91 | |||
6ccb40bab0 | |||
2b16a8a7a6 | |||
|
d051256839 | ||
68b32989fc | |||
21a41a8e03 | |||
9150958044 | |||
|
e358db44ca |
29
.gitea/workflows/job_lint.yml
Normal file
29
.gitea/workflows/job_lint.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
name: lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
- v4
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup deps
|
||||
run: go get -v ./...
|
||||
- name: run lint
|
||||
uses: https://github.com/golangci/golangci-lint-action@v6
|
||||
with:
|
||||
version: 'latest'
|
34
.gitea/workflows/job_test.yml
Normal file
34
.gitea/workflows/job_test.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
- v4
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
- v4
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup deps
|
||||
run: go get -v ./...
|
||||
- name: run test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
53
.gitea/workflows/job_tests.yml
Normal file
53
.gitea/workflows/job_tests.yml
Normal file
@@ -0,0 +1,53 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
- v4
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
- v4
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: checkout tests
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: master
|
||||
filter: 'blob:none'
|
||||
repository: unistack-org/micro-tests
|
||||
path: micro-tests
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup go work
|
||||
env:
|
||||
GOWORK: /workspace/${{ github.repository_owner }}/go.work
|
||||
run: |
|
||||
go work init
|
||||
go work use .
|
||||
go work use micro-tests
|
||||
- name: setup deps
|
||||
env:
|
||||
GOWORK: /workspace/${{ github.repository_owner }}/go.work
|
||||
run: go get -v ./...
|
||||
- name: run tests
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
GOWORK: /workspace/${{ github.repository_owner }}/go.work
|
||||
run: |
|
||||
cd micro-tests
|
||||
go test -mod readonly -v ./... || true
|
20
.github/renovate.json
vendored
20
.github/renovate.json
vendored
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"extends": [
|
||||
"config:base"
|
||||
],
|
||||
"postUpdateOptions": ["gomodTidy"],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["minor", "patch", "pin", "digest"],
|
||||
"automerge": true
|
||||
},
|
||||
{
|
||||
"groupName": "all deps",
|
||||
"separateMajorMinor": true,
|
||||
"groupSlug": "all",
|
||||
"packagePatterns": [
|
||||
"*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
13
.github/stale.sh
vendored
13
.github/stale.sh
vendored
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash -ex
|
||||
|
||||
export PATH=$PATH:$(pwd)/bin
|
||||
export GO111MODULE=on
|
||||
export GOBIN=$(pwd)/bin
|
||||
|
||||
#go get github.com/rvflash/goup@v0.4.1
|
||||
|
||||
#goup -v ./...
|
||||
#go get github.com/psampaz/go-mod-outdated@v0.6.0
|
||||
go list -u -m -mod=mod -json all | go-mod-outdated -update -direct -ci || true
|
||||
|
||||
#go list -u -m -json all | go-mod-outdated -update
|
46
.github/workflows/build.yml
vendored
46
.github/workflows/build.yml
vendored
@@ -1,46 +0,0 @@
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.16
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: deps
|
||||
run: go get -v -t -d ./...
|
||||
- name: test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
# args: --issues-exit-code=0
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
46
.github/workflows/pr.yml
vendored
46
.github/workflows/pr.yml
vendored
@@ -1,46 +0,0 @@
|
||||
name: prbuild
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.16
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: deps
|
||||
run: go get -v -t -d ./...
|
||||
- name: test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
# args: --issues-exit-code=0
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
39
.gitignore
vendored
Normal file
39
.gitignore
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
# Develop tools
|
||||
/.vscode/
|
||||
/.idea/
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
_build
|
||||
.DS_Store
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
# Test binary, build with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# vim temp files
|
||||
*~
|
||||
*.swp
|
||||
*.swo
|
5
.golangci.yml
Normal file
5
.golangci.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
run:
|
||||
concurrency: 8
|
||||
deadline: 5m
|
||||
issues-exit-code: 1
|
||||
tests: true
|
@@ -5,14 +5,14 @@ This plugin is a http client for micro.
|
||||
## Overview
|
||||
|
||||
The http client wraps `net/http` to provide a robust micro client with service discovery, load balancing and streaming.
|
||||
It complies with the [micro.Client](https://godoc.org/github.com/unistack-org/micro-client-http#Client) interface.
|
||||
It complies with the [micro.Client](https://godoc.org/go.unistack.org/micro-client-http/v3#Client) interface.
|
||||
|
||||
## Usage
|
||||
|
||||
### Use directly
|
||||
|
||||
```go
|
||||
import "github.com/unistack-org/micro-client-http"
|
||||
import "go.unistack.org/micro-client-http/v3"
|
||||
|
||||
service := micro.NewService(
|
||||
micro.Name("my.service"),
|
||||
|
16
go.mod
16
go.mod
@@ -1,5 +1,15 @@
|
||||
module github.com/unistack-org/micro-client-http/v3
|
||||
module go.unistack.org/micro-client-http/v3
|
||||
|
||||
go 1.16
|
||||
go 1.22
|
||||
|
||||
require github.com/unistack-org/micro/v3 v3.3.9
|
||||
toolchain go1.23.1
|
||||
|
||||
require go.unistack.org/micro/v3 v3.10.97
|
||||
|
||||
require (
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
|
||||
golang.org/x/sys v0.26.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 // indirect
|
||||
google.golang.org/grpc v1.67.1 // indirect
|
||||
google.golang.org/protobuf v1.35.1 // indirect
|
||||
)
|
||||
|
55
go.sum
55
go.sum
@@ -1,16 +1,39 @@
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
||||
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||
github.com/unistack-org/micro/v3 v3.3.9/go.mod h1:M3RGgKZX1OlTn0QB+3R1tlSoGwmEg6rb/Isr0lLYmjQ=
|
||||
golang.org/x/net v0.0.0-20210326220855-61e056675ecf/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
|
||||
go.unistack.org/micro/v3 v3.10.69 h1:V4g9LqUhzGab73U2aevnjtffCdJqGTuMfWY7fy4qGwI=
|
||||
go.unistack.org/micro/v3 v3.10.69/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
|
||||
go.unistack.org/micro/v3 v3.10.88 h1:MxlzP+77Y6Kphb3lzHxROL4XfE/WdCQMQpnPv4D9Z8U=
|
||||
go.unistack.org/micro/v3 v3.10.88/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
|
||||
go.unistack.org/micro/v3 v3.10.91 h1:vuJY4tXwpqimwIkEJ3TozMYNVQQs+C5QMlQWPgSY/YM=
|
||||
go.unistack.org/micro/v3 v3.10.91/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
|
||||
go.unistack.org/micro/v3 v3.10.97 h1:8l7fv+i06/PjPrBBhRC/ZQkWGIOuHPg3jJN0vktYE78=
|
||||
go.unistack.org/micro/v3 v3.10.97/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
|
||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be h1:LG9vZxsWGOmUKieR8wPAUR3u3MpnYFQZROPIMaXh7/A=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 h1:QCqS/PdaHTSWGvupk2F/ehwHtGc0/GYkT+3GAcR1CCc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI=
|
||||
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
|
||||
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
|
||||
google.golang.org/grpc v1.66.2 h1:3QdXkuq3Bkh7w+ywLdLvM56cmGvQHUMZpiCzt6Rqaoo=
|
||||
google.golang.org/grpc v1.66.2/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y=
|
||||
google.golang.org/grpc v1.67.0 h1:IdH9y6PF5MPSdAntIcpjQ+tXO41pcQsfZV2RxtQgVcw=
|
||||
google.golang.org/grpc v1.67.0/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
|
||||
google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E=
|
||||
google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
|
||||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
|
||||
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
|
740
http.go
740
http.go
@@ -1,77 +1,110 @@
|
||||
// Package http provides a http client
|
||||
package http
|
||||
package http // import "go.unistack.org/micro-client-http/v3"
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/broker"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/router"
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
"go.unistack.org/micro/v3/options"
|
||||
"go.unistack.org/micro/v3/selector"
|
||||
"go.unistack.org/micro/v3/semconv"
|
||||
"go.unistack.org/micro/v3/tracer"
|
||||
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultContentType = "application/json"
|
||||
)
|
||||
var DefaultContentType = "application/json"
|
||||
|
||||
/*
|
||||
func filterLabel(r []router.Route) []router.Route {
|
||||
// selector.FilterLabel("protocol", "http")
|
||||
return r
|
||||
}
|
||||
*/
|
||||
|
||||
type httpClient struct {
|
||||
opts client.Options
|
||||
dialer *net.Dialer
|
||||
httpcli *http.Client
|
||||
init bool
|
||||
funcPublish client.FuncPublish
|
||||
funcBatchPublish client.FuncBatchPublish
|
||||
funcCall client.FuncCall
|
||||
funcStream client.FuncStream
|
||||
httpcli *http.Client
|
||||
opts client.Options
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func newRequest(addr string, req client.Request, ct string, cf codec.Codec, msg interface{}, opts client.CallOptions) (*http.Request, error) {
|
||||
hreq := &http.Request{Method: http.MethodPost}
|
||||
body := "*" // as like google api http annotation
|
||||
|
||||
func newRequest(ctx context.Context, log logger.Logger, addr string, req client.Request, ct string, cf codec.Codec, msg interface{}, opts client.CallOptions) (*http.Request, error) {
|
||||
var tags []string
|
||||
var scheme string
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
hreq.URL = &url.URL{
|
||||
Scheme: "http",
|
||||
Host: addr,
|
||||
Path: req.Endpoint(),
|
||||
}
|
||||
hreq.Host = addr
|
||||
scheme = "http"
|
||||
} else {
|
||||
ep := req.Endpoint()
|
||||
if opts.Context != nil {
|
||||
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
||||
hreq.Method = m
|
||||
}
|
||||
if p, ok := opts.Context.Value(pathKey{}).(string); ok {
|
||||
ep = p
|
||||
}
|
||||
if b, ok := opts.Context.Value(bodyKey{}).(string); ok {
|
||||
body = b
|
||||
}
|
||||
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
||||
tags = t
|
||||
}
|
||||
var parameters map[string]map[string]string
|
||||
scheme := "http"
|
||||
method := http.MethodPost
|
||||
body := "*" // as like google api http annotation
|
||||
host := addr
|
||||
path := req.Endpoint()
|
||||
|
||||
u, err := url.Parse(addr)
|
||||
if err == nil {
|
||||
scheme = u.Scheme
|
||||
path = u.Path
|
||||
host = u.Host
|
||||
} else {
|
||||
u = &url.URL{Scheme: scheme, Path: path, Host: host}
|
||||
}
|
||||
|
||||
// nolint: nestif
|
||||
if opts.Context != nil {
|
||||
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
||||
method = m
|
||||
}
|
||||
hreq.URL, err = u.Parse(ep)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||
if p, ok := opts.Context.Value(pathKey{}).(string); ok {
|
||||
path += p
|
||||
}
|
||||
if b, ok := opts.Context.Value(bodyKey{}).(string); ok {
|
||||
body = b
|
||||
}
|
||||
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
||||
tags = t
|
||||
}
|
||||
if k, ok := opts.Context.Value(headerKey{}).([]string); ok && len(k) > 0 {
|
||||
if parameters == nil {
|
||||
parameters = make(map[string]map[string]string)
|
||||
}
|
||||
m, ok := parameters["header"]
|
||||
if !ok {
|
||||
m = make(map[string]string)
|
||||
parameters["header"] = m
|
||||
}
|
||||
for idx := 0; idx < len(k)/2; idx += 2 {
|
||||
m[k[idx]] = k[idx+1]
|
||||
}
|
||||
}
|
||||
if k, ok := opts.Context.Value(cookieKey{}).([]string); ok && len(k) > 0 {
|
||||
if parameters == nil {
|
||||
parameters = make(map[string]map[string]string)
|
||||
}
|
||||
m, ok := parameters["cookie"]
|
||||
if !ok {
|
||||
m = make(map[string]string)
|
||||
parameters["cookie"] = m
|
||||
}
|
||||
for idx := 0; idx < len(k)/2; idx += 2 {
|
||||
m[k[idx]] = k[idx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,197 +117,268 @@ func newRequest(addr string, req client.Request, ct string, cf codec.Codec, msg
|
||||
}
|
||||
}
|
||||
|
||||
path, nmsg, err := newPathRequest(hreq.URL.Path, hreq.Method, body, msg, tags)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||
if path == "" {
|
||||
path = req.Endpoint()
|
||||
}
|
||||
|
||||
if scheme != "" {
|
||||
hreq.URL, err = url.Parse(scheme + "://" + addr + path)
|
||||
u, err = u.Parse(path)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
var nmsg interface{}
|
||||
if len(u.Query()) > 0 {
|
||||
path, nmsg, err = newPathRequest(u.Path+"?"+u.RawQuery, method, body, msg, tags, parameters)
|
||||
} else {
|
||||
hreq.URL, err = url.Parse(addr + path)
|
||||
path, nmsg, err = newPathRequest(u.Path, method, body, msg, tags, parameters)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
var b []byte
|
||||
u, err = url.Parse(fmt.Sprintf("%s://%s%s", scheme, host, path))
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
if ct == "x-www-form-urlencoded" {
|
||||
fmt.Printf("XXXXX %#+v\n", nmsg)
|
||||
} else if nmsg != nil {
|
||||
b, err = cf.Marshal(nmsg)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||
var cookies []*http.Cookie
|
||||
header := make(http.Header)
|
||||
if opts.Context != nil {
|
||||
if md, ok := opts.Context.Value(metadataKey{}).(metadata.Metadata); ok {
|
||||
for k, v := range md {
|
||||
header.Set(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if opts.AuthToken != "" {
|
||||
header.Set(metadata.HeaderAuthorization, opts.AuthToken)
|
||||
}
|
||||
if opts.RequestMetadata != nil {
|
||||
for k, v := range opts.RequestMetadata {
|
||||
header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
for k, v := range md {
|
||||
header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// set timeout in nanoseconds
|
||||
if opts.StreamTimeout > time.Duration(0) {
|
||||
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.StreamTimeout))
|
||||
}
|
||||
if opts.RequestTimeout > time.Duration(0) {
|
||||
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.RequestTimeout))
|
||||
}
|
||||
|
||||
// set the content type for the request
|
||||
header.Set(metadata.HeaderContentType, ct)
|
||||
var v interface{}
|
||||
|
||||
for km, vm := range parameters {
|
||||
for k, required := range vm {
|
||||
v, err = rutil.StructFieldByPath(msg, k)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
if rutil.IsZero(v) {
|
||||
if required == "true" {
|
||||
return nil, errors.BadRequest("go.micro.client", "required field %s not set", k)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
switch km {
|
||||
case "header":
|
||||
header.Set(k, fmt.Sprintf("%v", v))
|
||||
case "cookie":
|
||||
cookies = append(cookies, &http.Cookie{Name: k, Value: fmt.Sprintf("%v", v)})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b, err := cf.Marshal(nmsg)
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
var hreq *http.Request
|
||||
if len(b) > 0 {
|
||||
hreq.Body = ioutil.NopCloser(bytes.NewBuffer(b))
|
||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), io.NopCloser(bytes.NewBuffer(b)))
|
||||
hreq.ContentLength = int64(len(b))
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", hreq.ContentLength))
|
||||
} else {
|
||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
hreq.Header = header
|
||||
for _, cookie := range cookies {
|
||||
hreq.AddCookie(cookie)
|
||||
}
|
||||
|
||||
if log.V(logger.DebugLevel) {
|
||||
log.Debug(ctx, fmt.Sprintf("request %s to %s with headers %v body %s", method, u.String(), hreq.Header, b))
|
||||
}
|
||||
|
||||
return hreq, nil
|
||||
}
|
||||
|
||||
func (h *httpClient) call(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||
header := make(http.Header, 2)
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
for k, v := range md {
|
||||
header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *httpClient) call(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||
ct := req.ContentType()
|
||||
|
||||
// set timeout in nanoseconds
|
||||
header.Set("Timeout", fmt.Sprintf("%d", opts.RequestTimeout))
|
||||
// set the content type for the request
|
||||
header.Set("Content-Type", ct)
|
||||
|
||||
var cf codec.Codec
|
||||
var err error
|
||||
// get codec
|
||||
switch ct {
|
||||
case "x-www-form-urlencoded":
|
||||
cf, err = h.newCodec(DefaultContentType)
|
||||
default:
|
||||
cf, err = h.newCodec(ct)
|
||||
if len(opts.ContentType) > 0 {
|
||||
ct = opts.ContentType
|
||||
}
|
||||
|
||||
cf, err := c.newCodec(ct)
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
return errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
hreq, err := newRequest(addr, req, ct, cf, req.Body(), opts)
|
||||
hreq, err := newRequest(ctx, c.opts.Logger, addr, req, ct, cf, req.Body(), opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hreq.Header = header
|
||||
|
||||
// make the request
|
||||
hrsp, err := h.httpcli.Do(hreq.WithContext(ctx))
|
||||
hrsp, err := c.httpcli.Do(hreq)
|
||||
if err != nil {
|
||||
switch err := err.(type) {
|
||||
case net.Error:
|
||||
if err.Timeout() {
|
||||
return errors.Timeout("go.micro.client", err.Error())
|
||||
}
|
||||
case *url.Error:
|
||||
if err, ok := err.Err.(net.Error); ok && err.Timeout() {
|
||||
return errors.Timeout("go.micro.client", err.Error())
|
||||
return errors.Timeout("go.micro.client", "%+v", err)
|
||||
}
|
||||
case net.Error:
|
||||
if err.Timeout() {
|
||||
return errors.Timeout("go.micro.client", "%+v", err)
|
||||
}
|
||||
}
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
defer hrsp.Body.Close()
|
||||
|
||||
return parseRsp(ctx, hrsp, cf, rsp, opts)
|
||||
return c.parseRsp(ctx, hrsp, rsp, opts)
|
||||
}
|
||||
|
||||
func (h *httpClient) stream(ctx context.Context, addr string, req client.Request, opts client.CallOptions) (client.Stream, error) {
|
||||
var header http.Header
|
||||
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
header = make(http.Header, len(md)+2)
|
||||
for k, v := range md {
|
||||
header.Set(k, v)
|
||||
}
|
||||
} else {
|
||||
header = make(http.Header, 2)
|
||||
}
|
||||
|
||||
func (c *httpClient) stream(ctx context.Context, addr string, req client.Request, opts client.CallOptions) (client.Stream, error) {
|
||||
ct := req.ContentType()
|
||||
// set timeout in nanoseconds
|
||||
header.Set("Timeout", fmt.Sprintf("%d", opts.RequestTimeout))
|
||||
// set the content type for the request
|
||||
header.Set("Content-Type", ct)
|
||||
if len(opts.ContentType) > 0 {
|
||||
ct = opts.ContentType
|
||||
}
|
||||
|
||||
// get codec
|
||||
cf, err := h.newCodec(req.ContentType())
|
||||
cf, err := c.newCodec(ct)
|
||||
if err != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
||||
return nil, errors.BadRequest("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
dialAddr := addr
|
||||
u, err := url.Parse(dialAddr)
|
||||
if err == nil && u.Scheme != "" && u.Host != "" {
|
||||
dialAddr = u.Host
|
||||
}
|
||||
cc, err := (h.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
||||
cc, err := (c.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error dialing: %v", err))
|
||||
return nil, errors.InternalServerError("go.micro.client", "Error dialing: %v", err)
|
||||
}
|
||||
|
||||
return &httpStream{
|
||||
address: addr,
|
||||
logger: c.opts.Logger,
|
||||
context: ctx,
|
||||
closed: make(chan bool),
|
||||
opts: opts,
|
||||
conn: cc,
|
||||
ct: ct,
|
||||
cf: cf,
|
||||
header: header,
|
||||
reader: bufio.NewReader(cc),
|
||||
request: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *httpClient) newCodec(ct string) (codec.Codec, error) {
|
||||
if c, ok := h.opts.Codecs[ct]; ok {
|
||||
return c, nil
|
||||
func (c *httpClient) newCodec(ct string) (codec.Codec, error) {
|
||||
c.RLock()
|
||||
|
||||
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
|
||||
ct = ct[:idx]
|
||||
}
|
||||
|
||||
if cf, ok := c.opts.Codecs[ct]; ok {
|
||||
c.RUnlock()
|
||||
return cf, nil
|
||||
}
|
||||
|
||||
c.RUnlock()
|
||||
return nil, codec.ErrUnknownContentType
|
||||
}
|
||||
|
||||
func (h *httpClient) Init(opts ...client.Option) error {
|
||||
if len(opts) == 0 && h.init {
|
||||
return nil
|
||||
}
|
||||
func (c *httpClient) Init(opts ...client.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&h.opts)
|
||||
o(&c.opts)
|
||||
}
|
||||
|
||||
if err := h.opts.Broker.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Tracer.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Router.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Logger.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Meter.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Transport.Init(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.funcCall = c.fnCall
|
||||
c.funcStream = c.fnStream
|
||||
c.funcPublish = c.fnPublish
|
||||
c.funcBatchPublish = c.fnBatchPublish
|
||||
|
||||
c.opts.Hooks.EachPrev(func(hook options.Hook) {
|
||||
switch h := hook.(type) {
|
||||
case client.HookCall:
|
||||
c.funcCall = h(c.funcCall)
|
||||
case client.HookStream:
|
||||
c.funcStream = h(c.funcStream)
|
||||
case client.HookPublish:
|
||||
c.funcPublish = h(c.funcPublish)
|
||||
case client.HookBatchPublish:
|
||||
c.funcBatchPublish = h(c.funcBatchPublish)
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpClient) Options() client.Options {
|
||||
return h.opts
|
||||
func (c *httpClient) Options() client.Options {
|
||||
return c.opts
|
||||
}
|
||||
|
||||
func (h *httpClient) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
|
||||
return newHTTPMessage(topic, msg, h.opts.ContentType, opts...)
|
||||
func (c *httpClient) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
|
||||
return newHTTPMessage(topic, msg, c.opts.ContentType, opts...)
|
||||
}
|
||||
|
||||
func (h *httpClient) NewRequest(service, method string, req interface{}, opts ...client.RequestOption) client.Request {
|
||||
return newHTTPRequest(service, method, req, h.opts.ContentType, opts...)
|
||||
func (c *httpClient) NewRequest(service, method string, req interface{}, opts ...client.RequestOption) client.Request {
|
||||
return newHTTPRequest(service, method, req, c.opts.ContentType, opts...)
|
||||
}
|
||||
|
||||
func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||
func (c *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||
ts := time.Now()
|
||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
|
||||
var sp tracer.Span
|
||||
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
|
||||
tracer.WithSpanKind(tracer.SpanKindClient),
|
||||
tracer.WithSpanLabels("endpoint", req.Endpoint()),
|
||||
)
|
||||
err := c.funcCall(ctx, req, rsp, opts...)
|
||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
|
||||
te := time.Since(ts)
|
||||
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||
|
||||
if me := errors.FromError(err); me == nil {
|
||||
sp.Finish()
|
||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "success", "code", strconv.Itoa(int(200))).Inc()
|
||||
} else {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "failure", "code", strconv.Itoa(int(me.Code))).Inc()
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||
// make a copy of call opts
|
||||
callOpts := h.opts.CallOptions
|
||||
callOpts := c.opts.CallOptions
|
||||
for _, opt := range opts {
|
||||
opt(&callOpts)
|
||||
}
|
||||
@@ -289,7 +393,7 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
||||
} else {
|
||||
// got a deadline so no need to setup context
|
||||
// but we need to set the timeout we pass along
|
||||
opt := client.WithRequestTimeout(d.Sub(time.Now()))
|
||||
opt := client.WithRequestTimeout(time.Until(d))
|
||||
opt(&callOpts)
|
||||
}
|
||||
|
||||
@@ -301,47 +405,31 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
||||
}
|
||||
|
||||
// make copy of call method
|
||||
hcall := h.call
|
||||
|
||||
// wrap the call in reverse
|
||||
for i := len(callOpts.CallWrappers); i > 0; i-- {
|
||||
hcall = callOpts.CallWrappers[i-1](hcall)
|
||||
}
|
||||
hcall := c.call
|
||||
|
||||
// use the router passed as a call option, or fallback to the rpc clients router
|
||||
if callOpts.Router == nil {
|
||||
callOpts.Router = h.opts.Router
|
||||
callOpts.Router = c.opts.Router
|
||||
}
|
||||
|
||||
if callOpts.Selector == nil {
|
||||
callOpts.Selector = h.opts.Selector
|
||||
callOpts.Selector = c.opts.Selector
|
||||
}
|
||||
|
||||
// inject proxy address
|
||||
// TODO: don't even bother using Lookup/Select in this case
|
||||
if len(h.opts.Proxy) > 0 {
|
||||
callOpts.Address = []string{h.opts.Proxy}
|
||||
if len(c.opts.Proxy) > 0 {
|
||||
callOpts.Address = []string{c.opts.Proxy}
|
||||
}
|
||||
|
||||
// lookup the route to send the reques to
|
||||
// TODO apply any filtering here
|
||||
routes, err := h.opts.Lookup(ctx, req, callOpts)
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
|
||||
// balance the list of nodes
|
||||
next, err := callOpts.Selector.Select(routes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var next selector.Next
|
||||
|
||||
// return errors.New("go.micro.client", "request timeout", 408)
|
||||
call := func(i int) error {
|
||||
// call backoff first. Someone may want an initial start delay
|
||||
t, err := callOpts.Backoff(ctx, req, i)
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
// only sleep if greater than 0
|
||||
@@ -349,12 +437,28 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
||||
time.Sleep(t)
|
||||
}
|
||||
|
||||
if next == nil {
|
||||
var routes []string
|
||||
// lookup the route to send the reques to
|
||||
// TODO apply any filtering here
|
||||
routes, err = c.opts.Lookup(ctx, req, callOpts)
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
// balance the list of nodes
|
||||
next, err = callOpts.Selector.Select(routes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
node := next()
|
||||
|
||||
// make the call
|
||||
err = hcall(ctx, node, req, rsp, callOpts)
|
||||
// record the result of the call to inform future routing decisions
|
||||
if verr := h.opts.Selector.Record(node, err); verr != nil {
|
||||
if verr := c.opts.Selector.Record(node, err); verr != nil {
|
||||
return verr
|
||||
}
|
||||
|
||||
@@ -399,25 +503,52 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
||||
return gerr
|
||||
}
|
||||
|
||||
func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||
func (c *httpClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||
ts := time.Now()
|
||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
|
||||
var sp tracer.Span
|
||||
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
|
||||
tracer.WithSpanKind(tracer.SpanKindClient),
|
||||
tracer.WithSpanLabels("endpoint", req.Endpoint()),
|
||||
)
|
||||
stream, err := c.funcStream(ctx, req, opts...)
|
||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
|
||||
te := time.Since(ts)
|
||||
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||
|
||||
if me := errors.FromError(err); me == nil {
|
||||
sp.Finish()
|
||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "success", "code", strconv.Itoa(int(200))).Inc()
|
||||
} else {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "failure", "code", strconv.Itoa(int(me.Code))).Inc()
|
||||
}
|
||||
|
||||
return stream, err
|
||||
}
|
||||
|
||||
func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||
var err error
|
||||
|
||||
// make a copy of call opts
|
||||
callOpts := h.opts.CallOptions
|
||||
for _, opt := range opts {
|
||||
opt(&callOpts)
|
||||
callOpts := c.opts.CallOptions
|
||||
for _, o := range opts {
|
||||
o(&callOpts)
|
||||
}
|
||||
|
||||
// check if we already have a deadline
|
||||
d, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
if !ok && callOpts.StreamTimeout > time.Duration(0) {
|
||||
var cancel context.CancelFunc
|
||||
// no deadline so we create a new one
|
||||
ctx, cancel = context.WithTimeout(ctx, callOpts.RequestTimeout)
|
||||
ctx, cancel = context.WithTimeout(ctx, callOpts.StreamTimeout)
|
||||
defer cancel()
|
||||
} else {
|
||||
// got a deadline so no need to setup context
|
||||
// but we need to set the timeout we pass along
|
||||
opt := client.WithRequestTimeout(d.Sub(time.Now()))
|
||||
opt(&callOpts)
|
||||
o := client.WithStreamTimeout(time.Until(d))
|
||||
o(&callOpts)
|
||||
}
|
||||
|
||||
// should we noop right here?
|
||||
@@ -429,10 +560,7 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
||||
|
||||
/*
|
||||
// make copy of call method
|
||||
hstream, err := h.stream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hstream := h.stream
|
||||
// wrap the call in reverse
|
||||
for i := len(callOpts.CallWrappers); i > 0; i-- {
|
||||
hstream = callOpts.CallWrappers[i-1](hstream)
|
||||
@@ -441,37 +569,26 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
||||
|
||||
// use the router passed as a call option, or fallback to the rpc clients router
|
||||
if callOpts.Router == nil {
|
||||
callOpts.Router = h.opts.Router
|
||||
callOpts.Router = c.opts.Router
|
||||
}
|
||||
|
||||
if callOpts.Selector == nil {
|
||||
callOpts.Selector = h.opts.Selector
|
||||
callOpts.Selector = c.opts.Selector
|
||||
}
|
||||
|
||||
// inject proxy address
|
||||
// TODO: don't even bother using Lookup/Select in this case
|
||||
if len(h.opts.Proxy) > 0 {
|
||||
callOpts.Address = []string{h.opts.Proxy}
|
||||
if len(c.opts.Proxy) > 0 {
|
||||
callOpts.Address = []string{c.opts.Proxy}
|
||||
}
|
||||
|
||||
// lookup the route to send the reques to
|
||||
// TODO apply any filtering here
|
||||
routes, err := h.opts.Lookup(ctx, req, callOpts)
|
||||
if err != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
|
||||
// balance the list of nodes
|
||||
next, err := callOpts.Selector.Select(routes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var next selector.Next
|
||||
|
||||
call := func(i int) (client.Stream, error) {
|
||||
// call backoff first. Someone may want an initial start delay
|
||||
t, err := callOpts.Backoff(ctx, req, i)
|
||||
if err != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
||||
t, cerr := callOpts.Backoff(ctx, req, i)
|
||||
if cerr != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", "%+v", cerr)
|
||||
}
|
||||
|
||||
// only sleep if greater than 0
|
||||
@@ -479,21 +596,37 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
||||
time.Sleep(t)
|
||||
}
|
||||
|
||||
if next == nil {
|
||||
var routes []string
|
||||
// lookup the route to send the reques to
|
||||
// TODO apply any filtering here
|
||||
routes, err = c.opts.Lookup(ctx, req, callOpts)
|
||||
if err != nil {
|
||||
return nil, errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
|
||||
// balance the list of nodes
|
||||
next, err = callOpts.Selector.Select(routes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
node := next()
|
||||
|
||||
stream, err := h.stream(ctx, node, req, callOpts)
|
||||
stream, cerr := c.stream(ctx, node, req, callOpts)
|
||||
|
||||
// record the result of the call to inform future routing decisions
|
||||
if verr := h.opts.Selector.Record(node, err); verr != nil {
|
||||
if verr := c.opts.Selector.Record(node, cerr); verr != nil {
|
||||
return nil, verr
|
||||
}
|
||||
|
||||
// try and transform the error to a go-micro error
|
||||
if verr, ok := err.(*errors.Error); ok {
|
||||
if verr, ok := cerr.(*errors.Error); ok {
|
||||
return nil, verr
|
||||
}
|
||||
|
||||
return stream, err
|
||||
return stream, cerr
|
||||
}
|
||||
|
||||
type response struct {
|
||||
@@ -506,8 +639,8 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
||||
|
||||
for i := 0; i <= callOpts.Retries; i++ {
|
||||
go func() {
|
||||
s, err := call(i)
|
||||
ch <- response{s, err}
|
||||
s, cerr := call(i)
|
||||
ch <- response{s, cerr}
|
||||
}()
|
||||
|
||||
select {
|
||||
@@ -535,86 +668,130 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
||||
return nil, grr
|
||||
}
|
||||
|
||||
func (h *httpClient) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||
options := client.NewPublishOptions(opts...)
|
||||
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(2)
|
||||
}
|
||||
md["Content-Type"] = p.ContentType()
|
||||
md["Micro-Topic"] = p.Topic()
|
||||
|
||||
cf, err := h.newCodec(p.ContentType())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
|
||||
var body []byte
|
||||
|
||||
// passed in raw data
|
||||
if d, ok := p.Payload().(*codec.Frame); ok {
|
||||
body = d.Data
|
||||
} else {
|
||||
b := bytes.NewBuffer(nil)
|
||||
if err := cf.Write(b, &codec.Message{Type: codec.Event}, p.Payload()); err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
body = b.Bytes()
|
||||
}
|
||||
|
||||
topic := p.Topic()
|
||||
|
||||
// get proxy
|
||||
if prx := os.Getenv("MICRO_PROXY"); len(prx) > 0 {
|
||||
options.Exchange = prx
|
||||
}
|
||||
|
||||
// get the exchange
|
||||
if len(options.Exchange) > 0 {
|
||||
topic = options.Exchange
|
||||
}
|
||||
|
||||
return h.opts.Broker.Publish(ctx, topic, &broker.Message{
|
||||
Header: md,
|
||||
Body: body,
|
||||
}, broker.PublishContext(ctx))
|
||||
func (c *httpClient) BatchPublish(ctx context.Context, p []client.Message, opts ...client.PublishOption) error {
|
||||
return c.funcBatchPublish(ctx, p, opts...)
|
||||
}
|
||||
|
||||
func (h *httpClient) String() string {
|
||||
func (c *httpClient) fnBatchPublish(ctx context.Context, p []client.Message, opts ...client.PublishOption) error {
|
||||
return c.publish(ctx, p, opts...)
|
||||
}
|
||||
|
||||
func (c *httpClient) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||
return c.funcPublish(ctx, p, opts...)
|
||||
}
|
||||
|
||||
func (c *httpClient) fnPublish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||
return c.publish(ctx, []client.Message{p}, opts...)
|
||||
}
|
||||
|
||||
func (c *httpClient) publish(ctx context.Context, ps []client.Message, opts ...client.PublishOption) error {
|
||||
var body []byte
|
||||
|
||||
options := client.NewPublishOptions(opts...)
|
||||
|
||||
// get proxy
|
||||
exchange := ""
|
||||
if v, ok := os.LookupEnv("MICRO_PROXY"); ok {
|
||||
exchange = v
|
||||
}
|
||||
// get the exchange
|
||||
if len(options.Exchange) > 0 {
|
||||
exchange = options.Exchange
|
||||
}
|
||||
|
||||
omd, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
omd = metadata.New(2)
|
||||
}
|
||||
|
||||
msgs := make([]*broker.Message, 0, len(ps))
|
||||
|
||||
for _, p := range ps {
|
||||
md := metadata.Copy(omd)
|
||||
md[metadata.HeaderContentType] = p.ContentType()
|
||||
topic := p.Topic()
|
||||
if len(exchange) > 0 {
|
||||
topic = exchange
|
||||
}
|
||||
md.Set(metadata.HeaderTopic, topic)
|
||||
iter := p.Metadata().Iterator()
|
||||
var k, v string
|
||||
for iter.Next(&k, &v) {
|
||||
md.Set(k, v)
|
||||
}
|
||||
|
||||
// passed in raw data
|
||||
if d, ok := p.Payload().(*codec.Frame); ok {
|
||||
body = d.Data
|
||||
} else {
|
||||
// use codec for payload
|
||||
cf, err := c.newCodec(p.ContentType())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
// set the body
|
||||
b, err := cf.Marshal(p.Payload())
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
body = b
|
||||
}
|
||||
|
||||
msgs = append(msgs, &broker.Message{Header: md, Body: body})
|
||||
}
|
||||
|
||||
return c.opts.Broker.BatchPublish(ctx, msgs,
|
||||
broker.PublishContext(ctx),
|
||||
broker.PublishBodyOnly(options.BodyOnly),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *httpClient) String() string {
|
||||
return "http"
|
||||
}
|
||||
|
||||
func (h *httpClient) Name() string {
|
||||
return h.opts.Name
|
||||
func (c *httpClient) Name() string {
|
||||
return c.opts.Name
|
||||
}
|
||||
|
||||
func NewClient(opts ...client.Option) client.Client {
|
||||
func NewClient(opts ...client.Option) *httpClient {
|
||||
options := client.NewOptions(opts...)
|
||||
|
||||
if len(options.ContentType) == 0 {
|
||||
options.ContentType = DefaultContentType
|
||||
}
|
||||
|
||||
rc := &httpClient{
|
||||
c := &httpClient{
|
||||
opts: options,
|
||||
}
|
||||
|
||||
dialer, ok := options.Context.Value(httpDialerKey{}).(*net.Dialer)
|
||||
if !ok {
|
||||
dialer = &net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
var dialer func(context.Context, string) (net.Conn, error)
|
||||
if v, ok := options.Context.Value(httpDialerKey{}).(*net.Dialer); ok {
|
||||
dialer = func(ctx context.Context, addr string) (net.Conn, error) {
|
||||
return v.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
}
|
||||
if options.ContextDialer != nil {
|
||||
dialer = options.ContextDialer
|
||||
}
|
||||
if dialer == nil {
|
||||
dialer = func(ctx context.Context, addr string) (net.Conn, error) {
|
||||
return (&net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
}
|
||||
|
||||
if httpcli, ok := options.Context.Value(httpClientKey{}).(*http.Client); ok {
|
||||
rc.httpcli = httpcli
|
||||
c.httpcli = httpcli
|
||||
} else {
|
||||
// TODO customTransport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: dialer.DialContext,
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return dialer(ctx, addr)
|
||||
},
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxConnsPerHost: 100,
|
||||
MaxIdleConns: 20,
|
||||
@@ -623,14 +800,13 @@ func NewClient(opts ...client.Option) client.Client {
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
TLSClientConfig: options.TLSConfig,
|
||||
}
|
||||
rc.httpcli = &http.Client{Transport: tr}
|
||||
c.httpcli = &http.Client{Transport: tr}
|
||||
}
|
||||
c := client.Client(rc)
|
||||
|
||||
// wrap in reverse
|
||||
for i := len(options.Wrappers); i > 0; i-- {
|
||||
c = options.Wrappers[i-1](c)
|
||||
}
|
||||
c.funcCall = c.fnCall
|
||||
c.funcStream = c.fnStream
|
||||
c.funcPublish = c.fnPublish
|
||||
c.funcBatchPublish = c.fnBatchPublish
|
||||
|
||||
return c
|
||||
}
|
||||
|
102
http_test.go
102
http_test.go
@@ -1,21 +1,102 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
Name string `json:"name"`
|
||||
Field1 string
|
||||
Field2 string
|
||||
Field3 int64
|
||||
func TestNestedPathPost(t *testing.T) {
|
||||
req := &request{Name: "first", Field1: "fieldval"}
|
||||
p, m, err := newPathRequest("/api/v1/xxxx", "POST", "*", req, []string{"json", "protobuf"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := u.String(); s != "/api/v1/xxxx" {
|
||||
t.Fatalf("nested path error %s", s)
|
||||
}
|
||||
_ = m
|
||||
}
|
||||
|
||||
type request struct {
|
||||
NestedTest *request `json:"nested_test,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Field1 string `json:"field1,omitempty"`
|
||||
ClientID string `json:",omitempty"`
|
||||
Field2 string `json:",omitempty"`
|
||||
Field3 int64 `json:",omitempty"`
|
||||
}
|
||||
|
||||
func TestNestedPath(t *testing.T) {
|
||||
req := &request{Name: "first", NestedTest: &request{Name: "second"}, Field1: "fieldval"}
|
||||
p, m, err := newPathRequest("/api/v1/{name}/{nested_test.name}", "PUT", "*", req, []string{"json", "protobuf"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := u.String(); s != "/api/v1/first/second" {
|
||||
t.Fatalf("nested path error %s", s)
|
||||
}
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Printf("m %#+v %s\n", m, b)
|
||||
}
|
||||
|
||||
func TestPathWithHeader(t *testing.T) {
|
||||
req := &request{Name: "vtolstov", Field1: "field1", ClientID: "1234567890"}
|
||||
p, m, err := newPathRequest(
|
||||
"/api/v1/test?Name={name}&Field1={field1}",
|
||||
"POST",
|
||||
"*",
|
||||
req,
|
||||
nil,
|
||||
map[string]map[string]string{"header": {"ClientID": "true"}},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m != nil {
|
||||
t.Fatal("new struct must be nil")
|
||||
}
|
||||
if u.Query().Get("Name") != "vtolstov" || u.Query().Get("Field1") != "field1" {
|
||||
t.Fatalf("invalid values %v", u.Query())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathValues(t *testing.T) {
|
||||
req := &request{Name: "vtolstov", Field1: "field1"}
|
||||
p, m, err := newPathRequest("/api/v1/test?Name={name}&Field1={field1}", "POST", "*", req, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = m
|
||||
if u.Query().Get("Name") != "vtolstov" || u.Query().Get("Field1") != "field1" {
|
||||
t.Fatalf("invalid values %v", u.Query())
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPath(t *testing.T) {
|
||||
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil)
|
||||
req := &request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -31,10 +112,9 @@ func TestValidPath(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInvalidPath(t *testing.T) {
|
||||
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||
p, m, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil)
|
||||
req := &request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||
s, _, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("path param must not be filled")
|
||||
t.Fatalf("path param must not be filled: %s", s)
|
||||
}
|
||||
_, _ = p, m
|
||||
}
|
||||
|
18
message.go
18
message.go
@@ -1,25 +1,29 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
type httpMessage struct {
|
||||
payload interface{}
|
||||
topic string
|
||||
contentType string
|
||||
payload interface{}
|
||||
opts client.MessageOptions
|
||||
}
|
||||
|
||||
func newHTTPMessage(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
|
||||
options := client.NewMessageOptions(opts...)
|
||||
if len(options.ContentType) == 0 {
|
||||
options.ContentType = contentType
|
||||
|
||||
if len(options.ContentType) > 0 {
|
||||
contentType = options.ContentType
|
||||
}
|
||||
|
||||
return &httpMessage{
|
||||
payload: payload,
|
||||
topic: topic,
|
||||
contentType: options.ContentType,
|
||||
contentType: contentType,
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,3 +38,7 @@ func (h *httpMessage) Topic() string {
|
||||
func (h *httpMessage) Payload() interface{} {
|
||||
return h.payload
|
||||
}
|
||||
|
||||
func (h *httpMessage) Metadata() metadata.Metadata {
|
||||
return h.opts.Metadata
|
||||
}
|
||||
|
43
options.go
43
options.go
@@ -4,7 +4,8 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -26,27 +27,28 @@ var (
|
||||
)
|
||||
|
||||
type poolMaxStreams struct{}
|
||||
type poolMaxIdle struct{}
|
||||
type codecsKey struct{}
|
||||
type tlsAuth struct{}
|
||||
type maxRecvMsgSizeKey struct{}
|
||||
type maxSendMsgSizeKey struct{}
|
||||
|
||||
// PoolMaxStreams maximum streams on a connectioin
|
||||
func PoolMaxStreams(n int) client.Option {
|
||||
return client.SetOption(poolMaxStreams{}, n)
|
||||
}
|
||||
|
||||
type poolMaxIdle struct{}
|
||||
|
||||
// PoolMaxIdle maximum idle conns of a pool
|
||||
func PoolMaxIdle(d int) client.Option {
|
||||
return client.SetOption(poolMaxIdle{}, d)
|
||||
}
|
||||
|
||||
type maxRecvMsgSizeKey struct{}
|
||||
|
||||
// MaxRecvMsgSize set the maximum size of message that client can receive.
|
||||
func MaxRecvMsgSize(s int) client.Option {
|
||||
return client.SetOption(maxRecvMsgSizeKey{}, s)
|
||||
}
|
||||
|
||||
type maxSendMsgSizeKey struct{}
|
||||
|
||||
// MaxSendMsgSize set the maximum size of message that client can send.
|
||||
func MaxSendMsgSize(s int) client.Option {
|
||||
return client.SetOption(maxSendMsgSizeKey{}, s)
|
||||
@@ -54,30 +56,37 @@ func MaxSendMsgSize(s int) client.Option {
|
||||
|
||||
type httpClientKey struct{}
|
||||
|
||||
// nolint: golint
|
||||
// HTTPClient pass http.Client option to client Call
|
||||
func HTTPClient(c *http.Client) client.Option {
|
||||
return client.SetOption(httpClientKey{}, c)
|
||||
}
|
||||
|
||||
type httpDialerKey struct{}
|
||||
|
||||
// nolint: golint
|
||||
// HTTPDialer pass net.Dialer option to client
|
||||
func HTTPDialer(d *net.Dialer) client.Option {
|
||||
return client.SetOption(httpDialerKey{}, d)
|
||||
}
|
||||
|
||||
type methodKey struct{}
|
||||
|
||||
// Method pass method option to client Call
|
||||
func Method(m string) client.CallOption {
|
||||
return client.SetCallOption(methodKey{}, m)
|
||||
}
|
||||
|
||||
type pathKey struct{}
|
||||
|
||||
// Path spcecifies path option to client Call
|
||||
func Path(p string) client.CallOption {
|
||||
return client.SetCallOption(pathKey{}, p)
|
||||
}
|
||||
|
||||
type bodyKey struct{}
|
||||
|
||||
// Body specifies body option to client Call
|
||||
func Body(b string) client.CallOption {
|
||||
return client.SetCallOption(bodyKey{}, b)
|
||||
}
|
||||
@@ -90,6 +99,28 @@ func ErrorMap(m map[string]interface{}) client.CallOption {
|
||||
|
||||
type structTagsKey struct{}
|
||||
|
||||
// StructTags pass tags slice option to client Call
|
||||
func StructTags(tags []string) client.CallOption {
|
||||
return client.SetCallOption(structTagsKey{}, tags)
|
||||
}
|
||||
|
||||
type metadataKey struct{}
|
||||
|
||||
// Metadata pass metadata to client Call
|
||||
func Metadata(md metadata.Metadata) client.CallOption {
|
||||
return client.SetCallOption(metadataKey{}, md)
|
||||
}
|
||||
|
||||
type cookieKey struct{}
|
||||
|
||||
// Cookie pass cookie to client Call
|
||||
func Cookie(cookies ...string) client.CallOption {
|
||||
return client.SetCallOption(cookieKey{}, cookies)
|
||||
}
|
||||
|
||||
type headerKey struct{}
|
||||
|
||||
// Header pass cookie to client Call
|
||||
func Header(headers ...string) client.CallOption {
|
||||
return client.SetCallOption(headerKey{}, headers)
|
||||
}
|
||||
|
@@ -1,8 +1,8 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
)
|
||||
|
||||
type httpRequest struct {
|
||||
@@ -15,7 +15,6 @@ type httpRequest struct {
|
||||
|
||||
func newHTTPRequest(service, method string, request interface{}, contentType string, opts ...client.RequestOption) client.Request {
|
||||
options := client.NewRequestOptions(opts...)
|
||||
|
||||
if len(options.ContentType) == 0 {
|
||||
options.ContentType = contentType
|
||||
}
|
||||
|
108
stream.go
108
stream.go
@@ -4,35 +4,34 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
)
|
||||
|
||||
// Implements the streamer interface
|
||||
type httpStream struct {
|
||||
sync.RWMutex
|
||||
address string
|
||||
opts client.CallOptions
|
||||
ct string
|
||||
cf codec.Codec
|
||||
context context.Context
|
||||
header http.Header
|
||||
seq uint64
|
||||
closed chan bool
|
||||
err error
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
cf codec.Codec
|
||||
context context.Context
|
||||
logger logger.Logger
|
||||
request client.Request
|
||||
closed chan bool
|
||||
reader *bufio.Reader
|
||||
address string
|
||||
ct string
|
||||
opts client.CallOptions
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
var (
|
||||
errShutdown = fmt.Errorf("connection is shut down")
|
||||
)
|
||||
var errShutdown = fmt.Errorf("connection is shut down")
|
||||
|
||||
func (h *httpStream) isClosed() bool {
|
||||
select {
|
||||
@@ -55,6 +54,10 @@ func (h *httpStream) Response() client.Response {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpStream) SendMsg(msg interface{}) error {
|
||||
return h.Send(msg)
|
||||
}
|
||||
|
||||
func (h *httpStream) Send(msg interface{}) error {
|
||||
h.Lock()
|
||||
defer h.Unlock()
|
||||
@@ -64,16 +67,18 @@ func (h *httpStream) Send(msg interface{}) error {
|
||||
return errShutdown
|
||||
}
|
||||
|
||||
hreq, err := newRequest(h.address, h.request, h.ct, h.cf, msg, h.opts)
|
||||
hreq, err := newRequest(h.context, h.logger, h.address, h.request, h.ct, h.cf, msg, h.opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hreq.Header = h.header
|
||||
|
||||
return hreq.Write(h.conn)
|
||||
}
|
||||
|
||||
func (h *httpStream) RecvMsg(msg interface{}) error {
|
||||
return h.Recv(msg)
|
||||
}
|
||||
|
||||
func (h *httpStream) Recv(msg interface{}) error {
|
||||
h.Lock()
|
||||
defer h.Unlock()
|
||||
@@ -85,11 +90,11 @@ func (h *httpStream) Recv(msg interface{}) error {
|
||||
|
||||
hrsp, err := http.ReadResponse(h.reader, new(http.Request))
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
defer hrsp.Body.Close()
|
||||
|
||||
return parseRsp(h.context, hrsp, h.cf, msg, h.opts)
|
||||
return h.parseRsp(h.context, h.logger, hrsp, h.cf, msg, h.opts)
|
||||
}
|
||||
|
||||
func (h *httpStream) Error() error {
|
||||
@@ -98,6 +103,10 @@ func (h *httpStream) Error() error {
|
||||
return h.err
|
||||
}
|
||||
|
||||
func (h *httpStream) CloseSend() error {
|
||||
return h.Close()
|
||||
}
|
||||
|
||||
func (h *httpStream) Close() error {
|
||||
select {
|
||||
case <-h.closed:
|
||||
@@ -107,3 +116,60 @@ func (h *httpStream) Close() error {
|
||||
return h.conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *httpStream) parseRsp(ctx context.Context, log logger.Logger, hrsp *http.Response, cf codec.Codec, rsp interface{}, opts client.CallOptions) error {
|
||||
var err error
|
||||
var buf []byte
|
||||
|
||||
// fast path return
|
||||
if hrsp.StatusCode == http.StatusNoContent {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
default:
|
||||
if hrsp.Body != nil {
|
||||
buf, err = io.ReadAll(hrsp.Body)
|
||||
if err != nil {
|
||||
if log.V(logger.ErrorLevel) {
|
||||
log.Error(ctx, "failed to read body", err)
|
||||
}
|
||||
return errors.InternalServerError("go.micro.client", "%s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
if log.V(logger.DebugLevel) {
|
||||
log.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header))
|
||||
}
|
||||
|
||||
if hrsp.StatusCode < 400 {
|
||||
if err = cf.Unmarshal(buf, rsp); err != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var rerr interface{}
|
||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||
if ok && errmap != nil {
|
||||
if rerr, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
||||
rerr, ok = errmap["default"].(error)
|
||||
}
|
||||
}
|
||||
if !ok || rerr == nil {
|
||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||
}
|
||||
|
||||
if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", cerr)
|
||||
}
|
||||
|
||||
if err, ok = rerr.(error); !ok {
|
||||
err = &Error{rerr}
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
355
util.go
355
util.go
@@ -3,38 +3,70 @@ package http
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
rutil "github.com/unistack-org/micro/v3/util/reflect"
|
||||
util "github.com/unistack-org/micro/v3/util/router"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/errors"
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
templateCache = make(map[string]util.Template)
|
||||
templateCache = make(map[string][]string)
|
||||
mu sync.RWMutex
|
||||
)
|
||||
|
||||
func newPathRequest(path string, method string, body string, msg interface{}, tags []string) (string, interface{}, error) {
|
||||
// Error struct holds error
|
||||
type Error struct {
|
||||
err interface{}
|
||||
}
|
||||
|
||||
// Error func for error interface
|
||||
func (err *Error) Error() string {
|
||||
return fmt.Sprintf("%v", err.err)
|
||||
}
|
||||
|
||||
func GetError(err error) interface{} {
|
||||
if rerr, ok := err.(*Error); ok {
|
||||
return rerr.err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func newPathRequest(path string, method string, body string, msg interface{}, tags []string, parameters map[string]map[string]string) (string, interface{}, error) {
|
||||
// parse via https://github.com/googleapis/googleapis/blob/master/google/api/http.proto definition
|
||||
tpl, err := newTemplate(path)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if len(tpl.Fields) > 0 && msg == nil {
|
||||
if len(tpl) > 0 && msg == nil {
|
||||
return "", nil, fmt.Errorf("nil message but path params requested: %v", path)
|
||||
}
|
||||
|
||||
fieldsmap := make(map[string]string, len(tpl.Fields))
|
||||
for _, v := range tpl.Fields {
|
||||
fieldsmap[v] = ""
|
||||
fieldsmapskip := make(map[string]struct{})
|
||||
fieldsmap := make(map[string]string, len(tpl))
|
||||
for _, v := range tpl {
|
||||
var vs, ve int
|
||||
for i := 0; i < len(v); i++ {
|
||||
switch v[i] {
|
||||
case '{':
|
||||
vs = i + 1
|
||||
case '}':
|
||||
ve = i
|
||||
}
|
||||
if ve != 0 {
|
||||
fieldsmap[v[vs:ve]] = ""
|
||||
vs = 0
|
||||
ve = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nmsg, err := rutil.Zero(msg)
|
||||
@@ -53,15 +85,25 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
||||
tnmsg = tnmsg.Elem()
|
||||
}
|
||||
|
||||
values := make(map[string]string)
|
||||
values := url.Values{}
|
||||
// copy cycle
|
||||
|
||||
cleanPath := make(map[string]bool)
|
||||
for i := 0; i < tmsg.NumField(); i++ {
|
||||
val := tmsg.Field(i)
|
||||
if val.IsZero() {
|
||||
continue
|
||||
}
|
||||
fld := tmsg.Type().Field(i)
|
||||
|
||||
// Skip unexported fields.
|
||||
if fld.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
/* check for empty PkgPath can be replaced with new method IsExported
|
||||
if !fld.IsExported() {
|
||||
continue
|
||||
}
|
||||
*/
|
||||
t := &tag{}
|
||||
for _, tn := range tags {
|
||||
ts, ok := fld.Tag.Lookup(tn)
|
||||
@@ -73,67 +115,177 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
||||
// special
|
||||
switch tn {
|
||||
case "protobuf": // special
|
||||
t = &tag{key: tn, name: tp[3][5:], opts: append(tp[:3], tp[4:]...)}
|
||||
for _, p := range tp {
|
||||
if idx := strings.Index(p, "name="); idx > 0 {
|
||||
t = &tag{key: tn, name: p[idx:]}
|
||||
}
|
||||
}
|
||||
default:
|
||||
t = &tag{key: tn, name: tp[0], opts: tp[1:]}
|
||||
t = &tag{key: tn, name: tp[0]}
|
||||
}
|
||||
|
||||
if t.name != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if t.name == "" {
|
||||
cname := t.name
|
||||
if cname == "" {
|
||||
cname = fld.Name
|
||||
// fallback to lowercase
|
||||
t.name = strings.ToLower(fld.Name)
|
||||
}
|
||||
if _, ok := parameters["header"][cname]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := parameters["cookie"][cname]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if !val.IsValid() || val.IsZero() {
|
||||
continue
|
||||
}
|
||||
|
||||
// nolint: gocritic, nestif
|
||||
if _, ok := fieldsmap[t.name]; ok {
|
||||
fieldsmap[t.name] = fmt.Sprintf("%v", val.Interface())
|
||||
} else if (body == "*" || body == t.name) && method != http.MethodGet {
|
||||
tnmsg.Field(i).Set(val)
|
||||
switch val.Type().Kind() {
|
||||
case reflect.Slice:
|
||||
for idx := 0; idx < val.Len(); idx++ {
|
||||
values.Add(t.name, getParam(val.Index(idx)))
|
||||
}
|
||||
fieldsmapskip[t.name] = struct{}{}
|
||||
default:
|
||||
fieldsmap[t.name] = getParam(val)
|
||||
}
|
||||
} else {
|
||||
values[t.name] = fmt.Sprintf("%v", val.Interface())
|
||||
for k, v := range fieldsmap {
|
||||
isSet := false
|
||||
if v != "" {
|
||||
continue
|
||||
}
|
||||
var clean []string
|
||||
fld := msg
|
||||
|
||||
parts := strings.Split(k, ".")
|
||||
|
||||
for idx := 0; idx < len(parts); idx++ {
|
||||
var nfld interface{}
|
||||
var name string
|
||||
if tags == nil {
|
||||
tags = []string{"json"}
|
||||
}
|
||||
tagsloop:
|
||||
for ti := 0; ti < len(tags); ti++ {
|
||||
name, nfld, err = rutil.StructFieldNameByTag(fld, tags[ti], parts[idx])
|
||||
if err == nil {
|
||||
clean = append(clean, name)
|
||||
break tagsloop
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
fld = nfld
|
||||
if len(parts)-1 == idx {
|
||||
isSet = true
|
||||
fieldsmap[k] = fmt.Sprintf("%v", fld)
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
if isSet {
|
||||
cleanPath[strings.Join(clean, ".")] = true
|
||||
}
|
||||
}
|
||||
for k := range cleanPath {
|
||||
if err = rutil.ZeroFieldByPath(nmsg, k); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
if (body == "*" || body == t.name) && method != http.MethodGet {
|
||||
if tnmsg.Field(i).CanSet() {
|
||||
tnmsg.Field(i).Set(val)
|
||||
}
|
||||
} else if method == http.MethodGet {
|
||||
if val.Type().Kind() == reflect.Slice {
|
||||
for idx := 0; idx < val.Len(); idx++ {
|
||||
values.Add(t.name, getParam(val.Index(idx)))
|
||||
}
|
||||
} else if !rutil.IsEmpty(val) {
|
||||
values.Add(t.name, getParam(val))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// check not filled stuff
|
||||
for k, v := range fieldsmap {
|
||||
if v == "" {
|
||||
_, ok := fieldsmapskip[k]
|
||||
if !ok && v == "" {
|
||||
return "", nil, fmt.Errorf("path param %s not filled", k)
|
||||
}
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
for _, fld := range tpl.Pool {
|
||||
|
||||
for _, fld := range tpl {
|
||||
_, _ = b.WriteRune('/')
|
||||
if v, ok := fieldsmap[fld]; ok {
|
||||
_, _ = b.WriteString(v)
|
||||
} else {
|
||||
// nolint: nestif
|
||||
var vs, ve, vf int
|
||||
var pholder bool
|
||||
for i := 0; i < len(fld); i++ {
|
||||
switch fld[i] {
|
||||
case '{':
|
||||
vs = i + 1
|
||||
case '}':
|
||||
ve = i
|
||||
}
|
||||
// nolint: nestif
|
||||
if vs > 0 && ve != 0 {
|
||||
if vm, ok := fieldsmap[fld[vs:ve]]; ok {
|
||||
if vm != "" {
|
||||
_, _ = b.WriteString(fld[vf : vs-1])
|
||||
_, _ = b.WriteString(vm)
|
||||
vf = ve + 1
|
||||
}
|
||||
} else {
|
||||
_, _ = b.WriteString(fld)
|
||||
}
|
||||
vs = 0
|
||||
ve = 0
|
||||
pholder = true
|
||||
}
|
||||
}
|
||||
if !pholder {
|
||||
_, _ = b.WriteString(fld)
|
||||
}
|
||||
}
|
||||
|
||||
idx := 0
|
||||
for k, v := range values {
|
||||
if idx == 0 {
|
||||
_, _ = b.WriteRune('?')
|
||||
} else {
|
||||
_, _ = b.WriteRune('&')
|
||||
}
|
||||
_, _ = b.WriteString(k)
|
||||
_, _ = b.WriteRune('=')
|
||||
_, _ = b.WriteString(v)
|
||||
idx++
|
||||
if len(values) > 0 {
|
||||
_, _ = b.WriteRune('?')
|
||||
_, _ = b.WriteString(values.Encode())
|
||||
}
|
||||
|
||||
if rutil.IsZero(nmsg) {
|
||||
// rutil.ZeroEmpty(tnmsg.Interface())
|
||||
|
||||
if rutil.IsZero(nmsg) && !isEmptyStruct(nmsg) {
|
||||
return b.String(), nil, nil
|
||||
}
|
||||
|
||||
return b.String(), nmsg, nil
|
||||
}
|
||||
|
||||
func newTemplate(path string) (util.Template, error) {
|
||||
func isEmptyStruct(v interface{}) bool {
|
||||
val := reflect.ValueOf(v)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
return val.Kind() == reflect.Struct && val.NumField() == 0
|
||||
}
|
||||
|
||||
func newTemplate(path string) ([]string, error) {
|
||||
if len(path) == 0 || path[0] != '/' {
|
||||
return nil, fmt.Errorf("path must starts with /")
|
||||
}
|
||||
mu.RLock()
|
||||
tpl, ok := templateCache[path]
|
||||
if ok {
|
||||
@@ -142,12 +294,7 @@ func newTemplate(path string) (util.Template, error) {
|
||||
}
|
||||
mu.RUnlock()
|
||||
|
||||
rule, err := util.Parse(path)
|
||||
if err != nil {
|
||||
return tpl, err
|
||||
}
|
||||
|
||||
tpl = rule.Compile()
|
||||
tpl = strings.Split(path[1:], "/")
|
||||
mu.Lock()
|
||||
templateCache[path] = tpl
|
||||
mu.Unlock()
|
||||
@@ -155,36 +302,84 @@ func newTemplate(path string) (util.Template, error) {
|
||||
return tpl, nil
|
||||
}
|
||||
|
||||
func parseRsp(ctx context.Context, hrsp *http.Response, cf codec.Codec, rsp interface{}, opts client.CallOptions) error {
|
||||
b, err := ioutil.ReadAll(hrsp.Body)
|
||||
if err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp interface{}, opts client.CallOptions) error {
|
||||
var err error
|
||||
var buf []byte
|
||||
|
||||
if hrsp.StatusCode < 400 {
|
||||
// unmarshal
|
||||
if err := cf.Unmarshal(b, rsp); err != nil {
|
||||
return errors.InternalServerError("go.micro.client", err.Error())
|
||||
}
|
||||
// fast path return
|
||||
if hrsp.StatusCode == http.StatusNoContent {
|
||||
return nil
|
||||
}
|
||||
|
||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||
if !ok || errmap == nil {
|
||||
// user not provide map of errors
|
||||
// id: req.Service() ??
|
||||
return errors.New("go.micro.client", string(b), int32(hrsp.StatusCode))
|
||||
if opts.ResponseMetadata != nil {
|
||||
*opts.ResponseMetadata = metadata.New(len(hrsp.Header))
|
||||
for k, v := range hrsp.Header {
|
||||
opts.ResponseMetadata.Set(k, strings.Join(v, ","))
|
||||
}
|
||||
}
|
||||
|
||||
if err, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
||||
err, ok = errmap["default"].(error)
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("go.micro.client", string(b), int32(hrsp.StatusCode))
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
default:
|
||||
ct := DefaultContentType
|
||||
|
||||
if htype := hrsp.Header.Get("Content-Type"); htype != "" {
|
||||
ct = htype
|
||||
}
|
||||
|
||||
if hrsp.Body != nil {
|
||||
buf, err = io.ReadAll(hrsp.Body)
|
||||
if err != nil {
|
||||
if h.opts.Logger.V(logger.ErrorLevel) {
|
||||
h.opts.Logger.Error(ctx, "failed to read body", err)
|
||||
}
|
||||
return errors.InternalServerError("go.micro.client", "%s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
cf, cerr := h.newCodec(ct)
|
||||
if cerr != nil {
|
||||
if h.opts.Logger.V(logger.DebugLevel) {
|
||||
h.opts.Logger.Debug(ctx, fmt.Sprintf("response with %v unknown content-type %s %s", hrsp.Header, ct, buf))
|
||||
}
|
||||
return errors.InternalServerError("go.micro.client", "%+v", cerr)
|
||||
}
|
||||
|
||||
if h.opts.Logger.V(logger.DebugLevel) {
|
||||
h.opts.Logger.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header))
|
||||
}
|
||||
|
||||
// succeseful response
|
||||
if hrsp.StatusCode < 400 {
|
||||
if err = cf.Unmarshal(buf, rsp); err != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// response with error
|
||||
var rerr interface{}
|
||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||
if ok && errmap != nil {
|
||||
rerr, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)]
|
||||
if !ok {
|
||||
rerr, ok = errmap["default"]
|
||||
}
|
||||
}
|
||||
|
||||
if !ok || rerr == nil {
|
||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||
}
|
||||
|
||||
if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
|
||||
return errors.InternalServerError("go.micro.client", "%+v", cerr)
|
||||
}
|
||||
|
||||
if err, ok = rerr.(error); !ok {
|
||||
err = &Error{rerr}
|
||||
}
|
||||
|
||||
if cerr := cf.Unmarshal(b, err); cerr != nil {
|
||||
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||
}
|
||||
|
||||
return err
|
||||
@@ -193,5 +388,27 @@ func parseRsp(ctx context.Context, hrsp *http.Response, cf codec.Codec, rsp inte
|
||||
type tag struct {
|
||||
key string
|
||||
name string
|
||||
opts []string
|
||||
}
|
||||
|
||||
func getParam(val reflect.Value) string {
|
||||
var v string
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
switch reflect.Indirect(val).Type().String() {
|
||||
case
|
||||
"wrapperspb.BoolValue",
|
||||
"wrapperspb.BytesValue",
|
||||
"wrapperspb.DoubleValue",
|
||||
"wrapperspb.FloatValue",
|
||||
"wrapperspb.Int32Value", "wrapperspb.Int64Value",
|
||||
"wrapperspb.StringValue",
|
||||
"wrapperspb.UInt32Value", "wrapperspb.UInt64Value":
|
||||
if eva := reflect.Indirect(val).FieldByName("Value"); eva.IsValid() {
|
||||
v = getParam(eva)
|
||||
}
|
||||
}
|
||||
default:
|
||||
v = fmt.Sprintf("%v", val.Interface())
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
103
util_test.go
103
util_test.go
@@ -1,32 +1,21 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTemplate(t *testing.T) {
|
||||
tpl, err := newTemplate("/v1/{ClientID}/list")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = tpl
|
||||
// fmt.Printf("%#+v\n", tpl.Pool)
|
||||
}
|
||||
|
||||
func TestNewPathRequest(t *testing.T) {
|
||||
func TestParsing(t *testing.T) {
|
||||
type Message struct {
|
||||
Name string `json:"name"`
|
||||
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
||||
Val2 int64
|
||||
Val3 []string
|
||||
IIN string `protobuf:"bytes,1,opt,name=iin,proto3" json:"iin"`
|
||||
}
|
||||
|
||||
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
||||
omsg := &Message{IIN: "5555"}
|
||||
|
||||
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
|
||||
for _, m := range []string{"POST"} {
|
||||
body := ""
|
||||
path, nmsg, err := newPathRequest("/v1/test", m, body, omsg, []string{"protobuf", "json"})
|
||||
path, nmsg, err := newPathRequest("/users/iin/{iin}/push-notifications", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -34,9 +23,77 @@ func TestNewPathRequest(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vals := u.Query()
|
||||
if v, ok := vals["name"]; !ok || v[0] != "test_name" {
|
||||
t.Fatalf("invalid path: %v nmsg: %v", path, nmsg)
|
||||
_ = nmsg
|
||||
if u.Path != "/users/iin/5555/push-notifications" {
|
||||
t.Fatalf("newPathRequest invalid path %s", u.Path)
|
||||
}
|
||||
if nmsg != nil {
|
||||
t.Fatalf("new message must be nil: %v\n", nmsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPathRequest(t *testing.T) {
|
||||
type Message struct {
|
||||
Name string `json:"name"`
|
||||
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
||||
Val3 []string
|
||||
Val2 int64
|
||||
}
|
||||
|
||||
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
||||
|
||||
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
|
||||
body := ""
|
||||
path, nmsg, err := newPathRequest("/v1/test", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch m {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
break
|
||||
case http.MethodGet:
|
||||
vals := u.Query()
|
||||
if v, ok := vals["name"]; !ok || v[0] != "test_name" {
|
||||
t.Fatalf("%s invalid path: %v nmsg: %v", m, path, nmsg)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPathRequestWithEmptyBody(t *testing.T) {
|
||||
val := struct{}{}
|
||||
cases := []string{
|
||||
"",
|
||||
"*",
|
||||
"{}",
|
||||
"nil",
|
||||
`{"type": "invalid"}`,
|
||||
}
|
||||
|
||||
for _, body := range cases {
|
||||
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
|
||||
path, nmsg, err := newPathRequest("/v1/test", m, body, val, []string{"protobuf", "json"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if nmsg == nil {
|
||||
t.Fatalf("invalid path: nil nmsg")
|
||||
}
|
||||
|
||||
u, err := url.Parse(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vals := u.Query()
|
||||
if len(vals) != 0 {
|
||||
t.Fatalf("invalid path: %v nmsg: %v", path, nmsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,8 +102,8 @@ func TestNewPathVarRequest(t *testing.T) {
|
||||
type Message struct {
|
||||
Name string `json:"name"`
|
||||
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
||||
Val2 int64
|
||||
Val3 []string
|
||||
Val2 int64
|
||||
}
|
||||
|
||||
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
||||
@@ -56,7 +113,7 @@ func TestNewPathVarRequest(t *testing.T) {
|
||||
if m != "GET" {
|
||||
body = "*"
|
||||
}
|
||||
path, nmsg, err := newPathRequest("/v1/test/{val1}", m, body, omsg, []string{"protobuf", "json"})
|
||||
path, nmsg, err := newPathRequest("/v1/test/{val1}", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -69,7 +126,7 @@ func TestNewPathVarRequest(t *testing.T) {
|
||||
t.Fatalf("invalid nmsg: %#+v\n", nmsg)
|
||||
}
|
||||
if nmsg.(*Message).Name != "test_name" {
|
||||
t.Fatalf("invalid nmsg: %v nmsg: %v", path, nmsg)
|
||||
t.Fatalf("invalid path: %v nmsg: %#+v", path, nmsg)
|
||||
}
|
||||
} else {
|
||||
vals := u.Query()
|
||||
|
Reference in New Issue
Block a user