Compare commits
No commits in common. "master" and "v3.7.3" have entirely different histories.
20
.github/workflows/autoapprove.yml
vendored
20
.github/workflows/autoapprove.yml
vendored
@ -1,20 +0,0 @@
|
|||||||
name: "autoapprove"
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
types: [assigned, opened, synchronize, reopened]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
pull-requests: write
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
autoapprove:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: approve
|
|
||||||
uses: hmarr/auto-approve-action@v3
|
|
||||||
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
|
|
||||||
id: approve
|
|
||||||
with:
|
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
21
.github/workflows/automerge.yml
vendored
21
.github/workflows/automerge.yml
vendored
@ -1,21 +0,0 @@
|
|||||||
name: "automerge"
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
types: [assigned, opened, synchronize, reopened]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
pull-requests: write
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
automerge:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: github.actor == 'vtolstov'
|
|
||||||
steps:
|
|
||||||
- name: merge
|
|
||||||
id: merge
|
|
||||||
run: gh pr merge --auto --merge "$PR_URL"
|
|
||||||
env:
|
|
||||||
PR_URL: ${{github.event.pull_request.html_url}}
|
|
||||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
|
13
.github/workflows/build.yml
vendored
13
.github/workflows/build.yml
vendored
@ -3,20 +3,19 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
- v3
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v3
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: 1.17
|
go-version: 1.16
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v2
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v2
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -32,9 +31,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v2
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v3.4.0
|
uses: golangci/golangci-lint-action@v2
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -9,7 +9,7 @@
|
|||||||
# the `language` matrix defined below to confirm you have the correct set of
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
# supported CodeQL languages.
|
# supported CodeQL languages.
|
||||||
#
|
#
|
||||||
name: "codeql"
|
name: "CodeQL"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@ -17,16 +17,16 @@ on:
|
|||||||
types:
|
types:
|
||||||
- completed
|
- completed
|
||||||
push:
|
push:
|
||||||
branches: [ master, v3 ]
|
branches: [ master ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ master, v3 ]
|
branches: [ master ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '34 1 * * 0'
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: analyze
|
name: Analyze
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
actions: read
|
actions: read
|
||||||
@ -42,15 +42,12 @@ jobs:
|
|||||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v2
|
||||||
- name: setup
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: 1.17
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: init
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@v2
|
uses: github/codeql-action/init@v1
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@ -60,8 +57,8 @@ jobs:
|
|||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: autobuild
|
- name: Autobuild
|
||||||
uses: github/codeql-action/autobuild@v2
|
uses: github/codeql-action/autobuild@v1
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 https://git.io/JvXDl
|
# 📚 https://git.io/JvXDl
|
||||||
@ -74,5 +71,5 @@ jobs:
|
|||||||
# make bootstrap
|
# make bootstrap
|
||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: analyze
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v2
|
uses: github/codeql-action/analyze@v1
|
||||||
|
73
.github/workflows/dependabot-automerge.yml
vendored
73
.github/workflows/dependabot-automerge.yml
vendored
@ -1,27 +1,66 @@
|
|||||||
name: "dependabot-automerge"
|
name: "prautomerge"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request_target:
|
workflow_run:
|
||||||
types: [assigned, opened, synchronize, reopened]
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
pull-requests: write
|
|
||||||
contents: write
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
automerge:
|
Dependabot-Automerge:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
if: github.actor == 'dependabot[bot]'
|
# Contains workaround to execute if dependabot updates the PR by checking for the base branch in the linked PR
|
||||||
|
# The the github.event.workflow_run.event value is 'push' and not 'pull_request'
|
||||||
|
# dont work with multiple workflows when last returns success
|
||||||
|
if: >-
|
||||||
|
github.event.workflow_run.conclusion == 'success'
|
||||||
|
&& github.actor == 'dependabot[bot]'
|
||||||
|
&& github.event.sender.login == 'dependabot[bot]'
|
||||||
|
&& github.event.sender.type == 'Bot'
|
||||||
|
&& (github.event.workflow_run.event == 'pull_request'
|
||||||
|
|| (github.event.workflow_run.event == 'push' && github.event.workflow_run.pull_requests[0].base.ref == github.event.repository.default_branch ))
|
||||||
steps:
|
steps:
|
||||||
- name: metadata
|
- name: Approve Changes and Merge changes if label 'dependencies' is set
|
||||||
id: metadata
|
uses: actions/github-script@v4
|
||||||
uses: dependabot/fetch-metadata@v1.3.6
|
|
||||||
with:
|
with:
|
||||||
github-token: "${{ secrets.TOKEN }}"
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: merge
|
script: |
|
||||||
id: merge
|
console.log(context.payload.workflow_run);
|
||||||
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
|
||||||
run: gh pr merge --auto --merge "$PR_URL"
|
var labelNames = await github.paginate(
|
||||||
env:
|
github.issues.listLabelsOnIssue,
|
||||||
PR_URL: ${{github.event.pull_request.html_url}}
|
{
|
||||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
repo: context.repo.repo,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
issue_number: context.payload.workflow_run.pull_requests[0].number,
|
||||||
|
},
|
||||||
|
(response) => response.data.map(
|
||||||
|
(label) => label.name
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(labelNames);
|
||||||
|
|
||||||
|
if (labelNames.includes('dependencies')) {
|
||||||
|
console.log('Found label');
|
||||||
|
|
||||||
|
await github.pulls.createReview({
|
||||||
|
repo: context.repo.repo,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
||||||
|
event: 'APPROVE'
|
||||||
|
});
|
||||||
|
console.log('Approved PR');
|
||||||
|
|
||||||
|
await github.pulls.merge({
|
||||||
|
repo: context.repo.repo,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Merged PR');
|
||||||
|
}
|
||||||
|
13
.github/workflows/pr.yml
vendored
13
.github/workflows/pr.yml
vendored
@ -3,20 +3,19 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
- v3
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v3
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: 1.17
|
go-version: 1.16
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v2
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v2
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -32,9 +31,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v2
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v3.4.0
|
uses: golangci/golangci-lint-action@v2
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
@ -5,14 +5,14 @@ This plugin is a http client for micro.
|
|||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
The http client wraps `net/http` to provide a robust micro client with service discovery, load balancing and streaming.
|
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/go.unistack.org/micro-client-http/v4#Client) interface.
|
It complies with the [micro.Client](https://godoc.org/github.com/unistack-org/micro-client-http#Client) interface.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Use directly
|
### Use directly
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "go.unistack.org/micro-client-http/v4"
|
import "github.com/unistack-org/micro-client-http"
|
||||||
|
|
||||||
service := micro.NewService(
|
service := micro.NewService(
|
||||||
micro.Name("my.service"),
|
micro.Name("my.service"),
|
||||||
|
6
go.mod
6
go.mod
@ -1,5 +1,5 @@
|
|||||||
module go.unistack.org/micro-client-http/v4
|
module github.com/unistack-org/micro-client-http/v3
|
||||||
|
|
||||||
go 1.19
|
go 1.16
|
||||||
|
|
||||||
require go.unistack.org/micro/v4 v4.0.18
|
require github.com/unistack-org/micro/v3 v3.7.1
|
||||||
|
40
go.sum
40
go.sum
@ -1,6 +1,34 @@
|
|||||||
go.unistack.org/micro/v4 v4.0.1 h1:xo1IxbVfgh8i0eY0VeYa3cbb13u5n/Mxnp3FOgWD4Jo=
|
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||||
go.unistack.org/micro/v4 v4.0.1/go.mod h1:p/J5UcSJjfHsWGT31uKoghQ5rUQZzQJBAFy+Z4+ZVMs=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
go.unistack.org/micro/v4 v4.0.6 h1:YFWvTh3VwyOd6NHYTQcf47n2TF5+p/EhpnbuBQX3qhk=
|
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
||||||
go.unistack.org/micro/v4 v4.0.6/go.mod h1:bVEYTlPi0EsdgZZt311bIroDg9ict7ky3C87dSCCAGk=
|
github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||||
go.unistack.org/micro/v4 v4.0.18 h1:b7WFwem8Nz1xBrRg5FeLnm9CE5gJseHyf9j0BhkiXW0=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
go.unistack.org/micro/v4 v4.0.18/go.mod h1:5+da5r835gP0WnNZbYUJDCvWpJ9Xc3IEGyp62e8o8R4=
|
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/unistack-org/micro-proto v0.0.9 h1:KrWLS4FUX7UAWNAilQf70uad6ZPf/0EudeddCXllRVc=
|
||||||
|
github.com/unistack-org/micro-proto v0.0.9/go.mod h1:Cckwmzd89gvS7ThxzZp9kQR/EOdksFQcsTAtDDyKwrg=
|
||||||
|
github.com/unistack-org/micro/v3 v3.7.1 h1:gjCon1U8i9upNgw9+iEgbZh2LCeBizDYotQ+THHV0lo=
|
||||||
|
github.com/unistack-org/micro/v3 v3.7.1/go.mod h1:gBoY6gvzeFiJTZ4FgDttGNSs4Y1+1PRg2cV1yTRMSlg=
|
||||||
|
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
|
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
|
||||||
|
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
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=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
331
http.go
331
http.go
@ -1,5 +1,5 @@
|
|||||||
// Package http provides a http client
|
// Package http provides a http client
|
||||||
package http // import "go.unistack.org/micro-client-http/v4"
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
@ -10,18 +10,16 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.unistack.org/micro/v4/client"
|
"github.com/unistack-org/micro/v3/broker"
|
||||||
"go.unistack.org/micro/v4/codec"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"go.unistack.org/micro/v4/errors"
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
"go.unistack.org/micro/v4/logger"
|
"github.com/unistack-org/micro/v3/errors"
|
||||||
"go.unistack.org/micro/v4/metadata"
|
"github.com/unistack-org/micro/v3/metadata"
|
||||||
"go.unistack.org/micro/v4/options"
|
|
||||||
"go.unistack.org/micro/v4/selector"
|
|
||||||
rutil "go.unistack.org/micro/v4/util/reflect"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var DefaultContentType = "application/json"
|
var DefaultContentType = "application/json"
|
||||||
@ -40,9 +38,8 @@ type httpClient struct {
|
|||||||
init bool
|
init bool
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
func newRequest(ctx context.Context, addr string, req client.Request, ct string, cf codec.Codec, msg interface{}, opts client.CallOptions) (*http.Request, error) {
|
||||||
var tags []string
|
var tags []string
|
||||||
var parameters map[string]map[string]string
|
|
||||||
scheme := "http"
|
scheme := "http"
|
||||||
method := http.MethodPost
|
method := http.MethodPost
|
||||||
body := "*" // as like google api http annotation
|
body := "*" // as like google api http annotation
|
||||||
@ -58,7 +55,6 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
u = &url.URL{Scheme: scheme, Path: path, Host: host}
|
u = &url.URL{Scheme: scheme, Path: path, Host: host}
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint: nestif
|
|
||||||
if opts.Context != nil {
|
if opts.Context != nil {
|
||||||
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
||||||
method = m
|
method = m
|
||||||
@ -72,32 +68,6 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
||||||
tags = t
|
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]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(tags) == 0 {
|
if len(tags) == 0 {
|
||||||
@ -120,9 +90,9 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
|
|
||||||
var nmsg interface{}
|
var nmsg interface{}
|
||||||
if len(u.Query()) > 0 {
|
if len(u.Query()) > 0 {
|
||||||
path, nmsg, err = newPathRequest(u.Path+"?"+u.RawQuery, method, body, msg, tags, parameters)
|
path, nmsg, err = newPathRequest(u.Path+"?"+u.RawQuery, method, body, msg, tags)
|
||||||
} else {
|
} else {
|
||||||
path, nmsg, err = newPathRequest(u.Path, method, body, msg, tags, parameters)
|
path, nmsg, err = newPathRequest(u.Path, method, body, msg, tags)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -134,64 +104,6 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
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[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if opts.AuthToken != "" {
|
|
||||||
header.Set(metadata.HeaderAuthorization, opts.AuthToken)
|
|
||||||
}
|
|
||||||
if opts.RequestMetadata != nil {
|
|
||||||
for k, v := range opts.RequestMetadata {
|
|
||||||
header[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
|
||||||
for k, v := range md {
|
|
||||||
header[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", err.Error())
|
|
||||||
}
|
|
||||||
if rutil.IsZero(v) {
|
|
||||||
if required == "true" {
|
|
||||||
return nil, errors.BadRequest("go.micro.client", fmt.Sprintf("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)
|
b, err := cf.Marshal(nmsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
@ -201,7 +113,6 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
if len(b) > 0 {
|
if len(b) > 0 {
|
||||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), ioutil.NopCloser(bytes.NewBuffer(b)))
|
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), ioutil.NopCloser(bytes.NewBuffer(b)))
|
||||||
hreq.ContentLength = int64(len(b))
|
hreq.ContentLength = int64(len(b))
|
||||||
header.Set("Content-Length", fmt.Sprintf("%d", hreq.ContentLength))
|
|
||||||
} else {
|
} else {
|
||||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
|
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
|
||||||
}
|
}
|
||||||
@ -210,15 +121,37 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
|
|||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
hreq.Header = header
|
header := make(http.Header)
|
||||||
for _, cookie := range cookies {
|
|
||||||
hreq.AddCookie(cookie)
|
if opts.Context != nil {
|
||||||
|
if md, ok := opts.Context.Value(metadataKey{}).(metadata.Metadata); ok {
|
||||||
|
for k, v := range md {
|
||||||
|
header.Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if log.V(logger.DebugLevel) {
|
if opts.AuthToken != "" {
|
||||||
log.Debug(ctx, fmt.Sprintf("request %s to %s with headers %v body %s", method, u.String(), hreq.Header, b))
|
hreq.Header.Set(metadata.HeaderAuthorization, opts.AuthToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
|
for k, v := range md {
|
||||||
|
hreq.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// set timeout in nanoseconds
|
||||||
|
if opts.StreamTimeout > time.Duration(0) {
|
||||||
|
hreq.Header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.StreamTimeout))
|
||||||
|
}
|
||||||
|
if opts.RequestTimeout > time.Duration(0) {
|
||||||
|
hreq.Header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.RequestTimeout))
|
||||||
|
}
|
||||||
|
|
||||||
|
// set the content type for the request
|
||||||
|
hreq.Header.Set(metadata.HeaderContentType, ct)
|
||||||
|
|
||||||
return hreq, nil
|
return hreq, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,9 +163,9 @@ func (h *httpClient) call(ctx context.Context, addr string, req client.Request,
|
|||||||
|
|
||||||
cf, err := h.newCodec(ct)
|
cf, err := h.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.BadRequest("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
hreq, err := newRequest(ctx, h.opts.Logger, addr, req, ct, cf, req.Body(), opts)
|
hreq, err := newRequest(ctx, addr, req, ct, cf, req.Body(), opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -267,7 +200,7 @@ func (h *httpClient) stream(ctx context.Context, addr string, req client.Request
|
|||||||
// get codec
|
// get codec
|
||||||
cf, err := h.newCodec(ct)
|
cf, err := h.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
cc, err := (h.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
cc, err := (h.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
||||||
@ -277,7 +210,6 @@ func (h *httpClient) stream(ctx context.Context, addr string, req client.Request
|
|||||||
|
|
||||||
return &httpStream{
|
return &httpStream{
|
||||||
address: addr,
|
address: addr,
|
||||||
logger: h.opts.Logger,
|
|
||||||
context: ctx,
|
context: ctx,
|
||||||
closed: make(chan bool),
|
closed: make(chan bool),
|
||||||
opts: opts,
|
opts: opts,
|
||||||
@ -304,7 +236,7 @@ func (h *httpClient) newCodec(ct string) (codec.Codec, error) {
|
|||||||
return nil, codec.ErrUnknownContentType
|
return nil, codec.ErrUnknownContentType
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) Init(opts ...options.Option) error {
|
func (h *httpClient) Init(opts ...client.Option) error {
|
||||||
if len(opts) == 0 && h.init {
|
if len(opts) == 0 && h.init {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -312,6 +244,9 @@ func (h *httpClient) Init(opts ...options.Option) error {
|
|||||||
o(&h.opts)
|
o(&h.opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := h.opts.Broker.Init(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := h.opts.Tracer.Init(); err != nil {
|
if err := h.opts.Tracer.Init(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -324,6 +259,9 @@ func (h *httpClient) Init(opts ...options.Option) error {
|
|||||||
if err := h.opts.Meter.Init(); err != nil {
|
if err := h.opts.Meter.Init(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := h.opts.Transport.Init(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -332,11 +270,15 @@ func (h *httpClient) Options() client.Options {
|
|||||||
return h.opts
|
return h.opts
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) NewRequest(service, method string, req interface{}, opts ...options.Option) client.Request {
|
func (h *httpClient) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
|
||||||
|
return newHTTPMessage(topic, msg, h.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...)
|
return newHTTPRequest(service, method, req, h.opts.ContentType, opts...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...options.Option) error {
|
func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||||
// make a copy of call opts
|
// make a copy of call opts
|
||||||
callOpts := h.opts.CallOptions
|
callOpts := h.opts.CallOptions
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
@ -353,9 +295,8 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
} else {
|
} else {
|
||||||
// got a deadline so no need to setup context
|
// got a deadline so no need to setup context
|
||||||
// but we need to set the timeout we pass along
|
// but we need to set the timeout we pass along
|
||||||
if err := options.Set(&callOpts, time.Until(d), ".RequestTimeout"); err != nil {
|
opt := client.WithRequestTimeout(time.Until(d))
|
||||||
return errors.New("go.micro.client", fmt.Sprintf("%v", err.Error()), 400)
|
opt(&callOpts)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should we noop right here?
|
// should we noop right here?
|
||||||
@ -369,9 +310,9 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
hcall := h.call
|
hcall := h.call
|
||||||
|
|
||||||
// wrap the call in reverse
|
// wrap the call in reverse
|
||||||
//for i := len(callOpts.CallWrappers); i > 0; i-- {
|
for i := len(callOpts.CallWrappers); i > 0; i-- {
|
||||||
// hcall = callOpts.CallWrappers[i-1](hcall)
|
hcall = callOpts.CallWrappers[i-1](hcall)
|
||||||
//}
|
}
|
||||||
|
|
||||||
// use the router passed as a call option, or fallback to the rpc clients router
|
// use the router passed as a call option, or fallback to the rpc clients router
|
||||||
if callOpts.Router == nil {
|
if callOpts.Router == nil {
|
||||||
@ -388,7 +329,18 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
callOpts.Address = []string{h.opts.Proxy}
|
callOpts.Address = []string{h.opts.Proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
var next selector.Next
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
// return errors.New("go.micro.client", "request timeout", 408)
|
// return errors.New("go.micro.client", "request timeout", 408)
|
||||||
call := func(i int) error {
|
call := func(i int) error {
|
||||||
@ -403,22 +355,6 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
time.Sleep(t)
|
time.Sleep(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
if next == nil {
|
|
||||||
var routes []string
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
node := next()
|
node := next()
|
||||||
|
|
||||||
// make the call
|
// make the call
|
||||||
@ -469,9 +405,7 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
return gerr
|
return gerr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...options.Option) (client.Stream, error) {
|
func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||||
var err error
|
|
||||||
|
|
||||||
// make a copy of call opts
|
// make a copy of call opts
|
||||||
callOpts := h.opts.CallOptions
|
callOpts := h.opts.CallOptions
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
@ -488,9 +422,8 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...opt
|
|||||||
} else {
|
} else {
|
||||||
// got a deadline so no need to setup context
|
// got a deadline so no need to setup context
|
||||||
// but we need to set the timeout we pass along
|
// but we need to set the timeout we pass along
|
||||||
if err = options.Set(&callOpts, time.Until(d), ".StreamTimeout"); err != nil {
|
o := client.WithStreamTimeout(time.Until(d))
|
||||||
return nil, errors.New("go.micro.client", fmt.Sprintf("%v", err.Error()), 400)
|
o(&callOpts)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should we noop right here?
|
// should we noop right here?
|
||||||
@ -524,7 +457,18 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...opt
|
|||||||
callOpts.Address = []string{h.opts.Proxy}
|
callOpts.Address = []string{h.opts.Proxy}
|
||||||
}
|
}
|
||||||
|
|
||||||
var next selector.Next
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
call := func(i int) (client.Stream, error) {
|
call := func(i int) (client.Stream, error) {
|
||||||
// call backoff first. Someone may want an initial start delay
|
// call backoff first. Someone may want an initial start delay
|
||||||
@ -538,22 +482,6 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...opt
|
|||||||
time.Sleep(t)
|
time.Sleep(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
if next == nil {
|
|
||||||
var routes []string
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
node := next()
|
node := next()
|
||||||
|
|
||||||
stream, cerr := h.stream(ctx, node, req, callOpts)
|
stream, cerr := h.stream(ctx, node, req, callOpts)
|
||||||
@ -610,6 +538,68 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...opt
|
|||||||
return nil, grr
|
return nil, grr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *httpClient) BatchPublish(ctx context.Context, p []client.Message, opts ...client.PublishOption) error {
|
||||||
|
return h.publish(ctx, p, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpClient) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||||
|
return h.publish(ctx, []client.Message{p}, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpClient) publish(ctx context.Context, ps []client.Message, opts ...client.PublishOption) error {
|
||||||
|
options := client.NewPublishOptions(opts...)
|
||||||
|
|
||||||
|
// get proxy
|
||||||
|
exchange := ""
|
||||||
|
if v, ok := os.LookupEnv("MICRO_PROXY"); ok {
|
||||||
|
exchange = v
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
md[metadata.HeaderTopic] = 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()
|
||||||
|
if len(exchange) > 0 {
|
||||||
|
topic = exchange
|
||||||
|
}
|
||||||
|
|
||||||
|
md.Set(metadata.HeaderTopic, topic)
|
||||||
|
msgs = append(msgs, &broker.Message{Header: md, Body: body})
|
||||||
|
}
|
||||||
|
|
||||||
|
return h.opts.Broker.BatchPublish(ctx, msgs,
|
||||||
|
broker.PublishContext(ctx),
|
||||||
|
broker.PublishBodyOnly(options.BodyOnly),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *httpClient) String() string {
|
func (h *httpClient) String() string {
|
||||||
return "http"
|
return "http"
|
||||||
}
|
}
|
||||||
@ -618,7 +608,7 @@ func (h *httpClient) Name() string {
|
|||||||
return h.opts.Name
|
return h.opts.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(opts ...options.Option) client.Client {
|
func NewClient(opts ...client.Option) client.Client {
|
||||||
options := client.NewOptions(opts...)
|
options := client.NewOptions(opts...)
|
||||||
|
|
||||||
if len(options.ContentType) == 0 {
|
if len(options.ContentType) == 0 {
|
||||||
@ -629,21 +619,11 @@ func NewClient(opts ...options.Option) client.Client {
|
|||||||
opts: options,
|
opts: options,
|
||||||
}
|
}
|
||||||
|
|
||||||
var dialer func(context.Context, string) (net.Conn, error)
|
dialer, ok := options.Context.Value(httpDialerKey{}).(*net.Dialer)
|
||||||
if v, ok := options.Context.Value(httpDialerKey{}).(*net.Dialer); ok {
|
if !ok {
|
||||||
dialer = func(ctx context.Context, addr string) (net.Conn, error) {
|
dialer = &net.Dialer{
|
||||||
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,
|
Timeout: 30 * time.Second,
|
||||||
KeepAlive: 30 * time.Second,
|
KeepAlive: 30 * time.Second,
|
||||||
}).DialContext(ctx, "tcp", addr)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -653,9 +633,7 @@ func NewClient(opts ...options.Option) client.Client {
|
|||||||
// TODO customTransport := http.DefaultTransport.(*http.Transport).Clone()
|
// TODO customTransport := http.DefaultTransport.(*http.Transport).Clone()
|
||||||
tr := &http.Transport{
|
tr := &http.Transport{
|
||||||
Proxy: http.ProxyFromEnvironment,
|
Proxy: http.ProxyFromEnvironment,
|
||||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
DialContext: dialer.DialContext,
|
||||||
return dialer(ctx, addr)
|
|
||||||
},
|
|
||||||
ForceAttemptHTTP2: true,
|
ForceAttemptHTTP2: true,
|
||||||
MaxConnsPerHost: 100,
|
MaxConnsPerHost: 100,
|
||||||
MaxIdleConns: 20,
|
MaxIdleConns: 20,
|
||||||
@ -668,5 +646,10 @@ func NewClient(opts ...options.Option) client.Client {
|
|||||||
}
|
}
|
||||||
c := client.Client(rc)
|
c := client.Client(rc)
|
||||||
|
|
||||||
|
// wrap in reverse
|
||||||
|
for i := len(options.Wrappers); i > 0; i-- {
|
||||||
|
c = options.Wrappers[i-1](c)
|
||||||
|
}
|
||||||
|
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
35
http_test.go
35
http_test.go
@ -9,39 +9,13 @@ import (
|
|||||||
type Request struct {
|
type Request struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Field1 string `json:"field1"`
|
Field1 string `json:"field1"`
|
||||||
ClientID string
|
|
||||||
Field2 string
|
Field2 string
|
||||||
Field3 int64
|
Field3 int64
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
func TestPathValues(t *testing.T) {
|
||||||
req := &Request{Name: "vtolstov", Field1: "field1"}
|
req := &Request{Name: "vtolstov", Field1: "field1"}
|
||||||
p, m, err := newPathRequest("/api/v1/test?Name={name}&Field1={field1}", "POST", "*", req, nil, nil)
|
p, m, err := newPathRequest("/api/v1/test?Name={name}&Field1={field1}", "POST", "*", req, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -57,7 +31,7 @@ func TestPathValues(t *testing.T) {
|
|||||||
|
|
||||||
func TestValidPath(t *testing.T) {
|
func TestValidPath(t *testing.T) {
|
||||||
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||||
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil, nil)
|
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -74,8 +48,9 @@ func TestValidPath(t *testing.T) {
|
|||||||
|
|
||||||
func TestInvalidPath(t *testing.T) {
|
func TestInvalidPath(t *testing.T) {
|
||||||
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
|
||||||
_, _, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil, nil)
|
p, m, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("path param must not be filled")
|
t.Fatalf("path param must not be filled")
|
||||||
}
|
}
|
||||||
|
_, _ = p, m
|
||||||
}
|
}
|
||||||
|
36
message.go
Normal file
36
message.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/unistack-org/micro/v3/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
type httpMessage struct {
|
||||||
|
payload interface{}
|
||||||
|
topic string
|
||||||
|
contentType string
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
return &httpMessage{
|
||||||
|
payload: payload,
|
||||||
|
topic: topic,
|
||||||
|
contentType: options.ContentType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpMessage) ContentType() string {
|
||||||
|
return h.contentType
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpMessage) Topic() string {
|
||||||
|
return h.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpMessage) Payload() interface{} {
|
||||||
|
return h.payload
|
||||||
|
}
|
73
options.go
73
options.go
@ -4,8 +4,8 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"go.unistack.org/micro/v4/metadata"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"go.unistack.org/micro/v4/options"
|
"github.com/unistack-org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -29,98 +29,77 @@ var (
|
|||||||
type poolMaxStreams struct{}
|
type poolMaxStreams struct{}
|
||||||
|
|
||||||
// PoolMaxStreams maximum streams on a connectioin
|
// PoolMaxStreams maximum streams on a connectioin
|
||||||
func PoolMaxStreams(n int) options.Option {
|
func PoolMaxStreams(n int) client.Option {
|
||||||
return options.ContextOption(poolMaxStreams{}, n)
|
return client.SetOption(poolMaxStreams{}, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
type poolMaxIdle struct{}
|
type poolMaxIdle struct{}
|
||||||
|
|
||||||
// PoolMaxIdle maximum idle conns of a pool
|
// PoolMaxIdle maximum idle conns of a pool
|
||||||
func PoolMaxIdle(d int) options.Option {
|
func PoolMaxIdle(d int) client.Option {
|
||||||
return options.ContextOption(poolMaxIdle{}, d)
|
return client.SetOption(poolMaxIdle{}, d)
|
||||||
}
|
}
|
||||||
|
|
||||||
type maxRecvMsgSizeKey struct{}
|
type maxRecvMsgSizeKey struct{}
|
||||||
|
|
||||||
// MaxRecvMsgSize set the maximum size of message that client can receive.
|
// MaxRecvMsgSize set the maximum size of message that client can receive.
|
||||||
func MaxRecvMsgSize(s int) options.Option {
|
func MaxRecvMsgSize(s int) client.Option {
|
||||||
return options.ContextOption(maxRecvMsgSizeKey{}, s)
|
return client.SetOption(maxRecvMsgSizeKey{}, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
type maxSendMsgSizeKey struct{}
|
type maxSendMsgSizeKey struct{}
|
||||||
|
|
||||||
// MaxSendMsgSize set the maximum size of message that client can send.
|
// MaxSendMsgSize set the maximum size of message that client can send.
|
||||||
func MaxSendMsgSize(s int) options.Option {
|
func MaxSendMsgSize(s int) client.Option {
|
||||||
return options.ContextOption(maxSendMsgSizeKey{}, s)
|
return client.SetOption(maxSendMsgSizeKey{}, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
type httpClientKey struct{}
|
type httpClientKey struct{}
|
||||||
|
|
||||||
// nolint: golint
|
// nolint: golint
|
||||||
// HTTPClient pass http.Client option to client Call
|
func HTTPClient(c *http.Client) client.Option {
|
||||||
func HTTPClient(c *http.Client) options.Option {
|
return client.SetOption(httpClientKey{}, c)
|
||||||
return options.ContextOption(httpClientKey{}, c)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type httpDialerKey struct{}
|
type httpDialerKey struct{}
|
||||||
|
|
||||||
// nolint: golint
|
// nolint: golint
|
||||||
// HTTPDialer pass net.Dialer option to client
|
func HTTPDialer(d *net.Dialer) client.Option {
|
||||||
func HTTPDialer(d *net.Dialer) options.Option {
|
return client.SetOption(httpDialerKey{}, d)
|
||||||
return options.ContextOption(httpDialerKey{}, d)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type methodKey struct{}
|
type methodKey struct{}
|
||||||
|
|
||||||
// Method pass method option to client Call
|
func Method(m string) client.CallOption {
|
||||||
func Method(m string) options.Option {
|
return client.SetCallOption(methodKey{}, m)
|
||||||
return options.ContextOption(methodKey{}, m)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type pathKey struct{}
|
type pathKey struct{}
|
||||||
|
|
||||||
// Path spcecifies path option to client Call
|
func Path(p string) client.CallOption {
|
||||||
func Path(p string) options.Option {
|
return client.SetCallOption(pathKey{}, p)
|
||||||
return options.ContextOption(pathKey{}, p)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type bodyKey struct{}
|
type bodyKey struct{}
|
||||||
|
|
||||||
// Body specifies body option to client Call
|
func Body(b string) client.CallOption {
|
||||||
func Body(b string) options.Option {
|
return client.SetCallOption(bodyKey{}, b)
|
||||||
return options.ContextOption(bodyKey{}, b)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type errorMapKey struct{}
|
type errorMapKey struct{}
|
||||||
|
|
||||||
func ErrorMap(m map[string]interface{}) options.Option {
|
func ErrorMap(m map[string]interface{}) client.CallOption {
|
||||||
return options.ContextOption(errorMapKey{}, m)
|
return client.SetCallOption(errorMapKey{}, m)
|
||||||
}
|
}
|
||||||
|
|
||||||
type structTagsKey struct{}
|
type structTagsKey struct{}
|
||||||
|
|
||||||
// StructTags pass tags slice option to client Call
|
func StructTags(tags []string) client.CallOption {
|
||||||
func StructTags(tags []string) options.Option {
|
return client.SetCallOption(structTagsKey{}, tags)
|
||||||
return options.ContextOption(structTagsKey{}, tags)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type metadataKey struct{}
|
type metadataKey struct{}
|
||||||
|
|
||||||
// Metadata pass metadata to client Call
|
func Metadata(md metadata.Metadata) client.CallOption {
|
||||||
func Metadata(md metadata.Metadata) options.Option {
|
return client.SetCallOption(metadataKey{}, md)
|
||||||
return options.ContextOption(metadataKey{}, md)
|
|
||||||
}
|
|
||||||
|
|
||||||
type cookieKey struct{}
|
|
||||||
|
|
||||||
// Cookie pass cookie to client Call
|
|
||||||
func Cookie(cookies ...string) options.Option {
|
|
||||||
return options.ContextOption(cookieKey{}, cookies)
|
|
||||||
}
|
|
||||||
|
|
||||||
type headerKey struct{}
|
|
||||||
|
|
||||||
// Header pass cookie to client Call
|
|
||||||
func Header(headers ...string) options.Option {
|
|
||||||
return options.ContextOption(headerKey{}, headers)
|
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"go.unistack.org/micro/v4/client"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"go.unistack.org/micro/v4/codec"
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
"go.unistack.org/micro/v4/options"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpRequest struct {
|
type httpRequest struct {
|
||||||
@ -14,7 +13,7 @@ type httpRequest struct {
|
|||||||
opts client.RequestOptions
|
opts client.RequestOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
func newHTTPRequest(service, method string, request interface{}, contentType string, opts ...options.Option) client.Request {
|
func newHTTPRequest(service, method string, request interface{}, contentType string, opts ...client.RequestOption) client.Request {
|
||||||
options := client.NewRequestOptions(opts...)
|
options := client.NewRequestOptions(opts...)
|
||||||
if len(options.ContentType) == 0 {
|
if len(options.ContentType) == 0 {
|
||||||
options.ContentType = contentType
|
options.ContentType = contentType
|
||||||
|
68
stream.go
68
stream.go
@ -9,10 +9,9 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"go.unistack.org/micro/v4/client"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"go.unistack.org/micro/v4/codec"
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
"go.unistack.org/micro/v4/errors"
|
"github.com/unistack-org/micro/v3/errors"
|
||||||
"go.unistack.org/micro/v4/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Implements the streamer interface
|
// Implements the streamer interface
|
||||||
@ -21,7 +20,6 @@ type httpStream struct {
|
|||||||
conn net.Conn
|
conn net.Conn
|
||||||
cf codec.Codec
|
cf codec.Codec
|
||||||
context context.Context
|
context context.Context
|
||||||
logger logger.Logger
|
|
||||||
request client.Request
|
request client.Request
|
||||||
closed chan bool
|
closed chan bool
|
||||||
reader *bufio.Reader
|
reader *bufio.Reader
|
||||||
@ -54,10 +52,6 @@ func (h *httpStream) Response() client.Response {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpStream) SendMsg(msg interface{}) error {
|
|
||||||
return h.Send(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpStream) Send(msg interface{}) error {
|
func (h *httpStream) Send(msg interface{}) error {
|
||||||
h.Lock()
|
h.Lock()
|
||||||
defer h.Unlock()
|
defer h.Unlock()
|
||||||
@ -67,7 +61,7 @@ func (h *httpStream) Send(msg interface{}) error {
|
|||||||
return errShutdown
|
return errShutdown
|
||||||
}
|
}
|
||||||
|
|
||||||
hreq, err := newRequest(h.context, h.logger, h.address, h.request, h.ct, h.cf, msg, h.opts)
|
hreq, err := newRequest(h.context, h.address, h.request, h.ct, h.cf, msg, h.opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -75,10 +69,6 @@ func (h *httpStream) Send(msg interface{}) error {
|
|||||||
return hreq.Write(h.conn)
|
return hreq.Write(h.conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpStream) RecvMsg(msg interface{}) error {
|
|
||||||
return h.Recv(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpStream) Recv(msg interface{}) error {
|
func (h *httpStream) Recv(msg interface{}) error {
|
||||||
h.Lock()
|
h.Lock()
|
||||||
defer h.Unlock()
|
defer h.Unlock()
|
||||||
@ -94,7 +84,7 @@ func (h *httpStream) Recv(msg interface{}) error {
|
|||||||
}
|
}
|
||||||
defer hrsp.Body.Close()
|
defer hrsp.Body.Close()
|
||||||
|
|
||||||
return h.parseRsp(h.context, h.logger, hrsp, h.cf, msg, h.opts)
|
return h.parseRsp(h.context, hrsp, h.cf, msg, h.opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpStream) Error() error {
|
func (h *httpStream) Error() error {
|
||||||
@ -103,10 +93,6 @@ func (h *httpStream) Error() error {
|
|||||||
return h.err
|
return h.err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpStream) CloseSend() error {
|
|
||||||
return h.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpStream) Close() error {
|
func (h *httpStream) Close() error {
|
||||||
select {
|
select {
|
||||||
case <-h.closed:
|
case <-h.closed:
|
||||||
@ -117,57 +103,41 @@ func (h *httpStream) Close() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpStream) parseRsp(ctx context.Context, log logger.Logger, hrsp *http.Response, cf codec.Codec, rsp interface{}, opts client.CallOptions) error {
|
func (h *httpStream) parseRsp(ctx context.Context, hrsp *http.Response, cf codec.Codec, rsp interface{}, opts client.CallOptions) error {
|
||||||
var err error
|
var err error
|
||||||
var buf []byte
|
|
||||||
|
|
||||||
// fast path return
|
|
||||||
if hrsp.StatusCode == http.StatusNoContent {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
err = ctx.Err()
|
err = ctx.Err()
|
||||||
default:
|
default:
|
||||||
if hrsp.Body != nil {
|
// fast path return
|
||||||
buf, err = io.ReadAll(hrsp.Body)
|
if hrsp.StatusCode == http.StatusNoContent {
|
||||||
if err != nil {
|
return nil
|
||||||
if log.V(logger.ErrorLevel) {
|
|
||||||
log.Error(ctx, "failed to read body", err)
|
|
||||||
}
|
|
||||||
return errors.InternalServerError("go.micro.client", string(buf))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if log.V(logger.DebugLevel) {
|
|
||||||
log.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if hrsp.StatusCode < 400 {
|
if hrsp.StatusCode < 400 {
|
||||||
if err = cf.Unmarshal(buf, rsp); err != nil {
|
if err = cf.ReadBody(hrsp.Body, rsp); err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var rerr interface{}
|
|
||||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||||
if ok && errmap != nil {
|
if ok && errmap != nil {
|
||||||
if rerr, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
if err, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
||||||
rerr, ok = errmap["default"].(error)
|
err, ok = errmap["default"].(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !ok || rerr == nil {
|
if !ok || err == nil {
|
||||||
|
buf, cerr := io.ReadAll(hrsp.Body)
|
||||||
|
if cerr != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
|
}
|
||||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||||
}
|
}
|
||||||
|
|
||||||
if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
|
if cerr := cf.ReadBody(hrsp.Body, err); cerr != nil {
|
||||||
return errors.InternalServerError("go.micro.client", cerr.Error())
|
err = errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
}
|
|
||||||
|
|
||||||
if err, ok = rerr.(error); !ok {
|
|
||||||
err = &Error{rerr}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
120
util.go
120
util.go
@ -10,11 +10,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"go.unistack.org/micro/v4/client"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"go.unistack.org/micro/v4/errors"
|
"github.com/unistack-org/micro/v3/errors"
|
||||||
"go.unistack.org/micro/v4/logger"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
"go.unistack.org/micro/v4/metadata"
|
rutil "github.com/unistack-org/micro/v3/util/reflect"
|
||||||
rutil "go.unistack.org/micro/v4/util/reflect"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -39,7 +38,7 @@ func GetError(err error) interface{} {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPathRequest(path string, method string, body string, msg interface{}, tags []string, parameters map[string]map[string]string) (string, interface{}, error) {
|
func newPathRequest(path string, method string, body string, msg interface{}, tags []string) (string, interface{}, error) {
|
||||||
// parse via https://github.com/googleapis/googleapis/blob/master/google/api/http.proto definition
|
// parse via https://github.com/googleapis/googleapis/blob/master/google/api/http.proto definition
|
||||||
tpl, err := newTemplate(path)
|
tpl, err := newTemplate(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -93,15 +92,7 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
fld := tmsg.Type().Field(i)
|
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{}
|
t := &tag{}
|
||||||
for _, tn := range tags {
|
for _, tn := range tags {
|
||||||
ts, ok := fld.Tag.Lookup(tn)
|
ts, ok := fld.Tag.Lookup(tn)
|
||||||
@ -126,18 +117,10 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cname := t.name
|
if t.name == "" {
|
||||||
if cname == "" {
|
|
||||||
cname = fld.Name
|
|
||||||
// fallback to lowercase
|
// fallback to lowercase
|
||||||
t.name = strings.ToLower(fld.Name)
|
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() {
|
if !val.IsValid() || val.IsZero() {
|
||||||
continue
|
continue
|
||||||
@ -148,11 +131,11 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
switch val.Type().Kind() {
|
switch val.Type().Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
for idx := 0; idx < val.Len(); idx++ {
|
for idx := 0; idx < val.Len(); idx++ {
|
||||||
values.Add(t.name, getParam(val.Index(idx)))
|
values.Add(t.name, fmt.Sprintf("%v", val.Index(idx).Interface()))
|
||||||
}
|
}
|
||||||
fieldsmapskip[t.name] = struct{}{}
|
fieldsmapskip[t.name] = struct{}{}
|
||||||
default:
|
default:
|
||||||
fieldsmap[t.name] = getParam(val)
|
fieldsmap[t.name] = fmt.Sprintf("%v", val.Interface())
|
||||||
}
|
}
|
||||||
} else if (body == "*" || body == t.name) && method != http.MethodGet {
|
} else if (body == "*" || body == t.name) && method != http.MethodGet {
|
||||||
if tnmsg.Field(i).CanSet() {
|
if tnmsg.Field(i).CanSet() {
|
||||||
@ -161,10 +144,10 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
} else {
|
} else {
|
||||||
if val.Type().Kind() == reflect.Slice {
|
if val.Type().Kind() == reflect.Slice {
|
||||||
for idx := 0; idx < val.Len(); idx++ {
|
for idx := 0; idx < val.Len(); idx++ {
|
||||||
values.Add(t.name, getParam(val.Index(idx)))
|
values.Add(t.name, fmt.Sprintf("%v", val.Index(idx).Interface()))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
values.Add(t.name, getParam(val))
|
values.Add(t.name, fmt.Sprintf("%v", val.Interface()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -217,21 +200,13 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
_, _ = b.WriteString(values.Encode())
|
_, _ = b.WriteString(values.Encode())
|
||||||
}
|
}
|
||||||
|
|
||||||
if rutil.IsZero(nmsg) && !isEmptyStruct(nmsg) {
|
if rutil.IsZero(nmsg) {
|
||||||
return b.String(), nil, nil
|
return b.String(), nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return b.String(), nmsg, nil
|
return b.String(), nmsg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
func newTemplate(path string) ([]string, error) {
|
||||||
if len(path) == 0 || path[0] != '/' {
|
if len(path) == 0 || path[0] != '/' {
|
||||||
return nil, fmt.Errorf("path must starts with /")
|
return nil, fmt.Errorf("path must starts with /")
|
||||||
@ -254,55 +229,39 @@ func newTemplate(path string) ([]string, error) {
|
|||||||
|
|
||||||
func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp interface{}, opts client.CallOptions) error {
|
func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp interface{}, opts client.CallOptions) error {
|
||||||
var err error
|
var err error
|
||||||
var buf []byte
|
|
||||||
|
|
||||||
// fast path return
|
|
||||||
if hrsp.StatusCode == http.StatusNoContent {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.ResponseMetadata != nil {
|
|
||||||
*opts.ResponseMetadata = metadata.New(len(hrsp.Header))
|
|
||||||
for k, v := range hrsp.Header {
|
|
||||||
opts.ResponseMetadata.Set(k, strings.Join(v, ","))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
err = ctx.Err()
|
err = ctx.Err()
|
||||||
default:
|
default:
|
||||||
|
// fast path return
|
||||||
|
if hrsp.StatusCode == http.StatusNoContent {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
ct := DefaultContentType
|
ct := DefaultContentType
|
||||||
|
|
||||||
if htype := hrsp.Header.Get("Content-Type"); htype != "" {
|
if htype := hrsp.Header.Get("Content-Type"); htype != "" {
|
||||||
ct = htype
|
ct = htype
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cf, cerr := h.newCodec(ct)
|
||||||
|
if hrsp.StatusCode >= 400 && cerr != nil {
|
||||||
|
var buf []byte
|
||||||
if hrsp.Body != nil {
|
if hrsp.Body != nil {
|
||||||
buf, err = io.ReadAll(hrsp.Body)
|
buf, err = io.ReadAll(hrsp.Body)
|
||||||
if err != nil {
|
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
if h.opts.Logger.V(logger.ErrorLevel) {
|
h.opts.Logger.Errorf(ctx, "failed to read body: %v", err)
|
||||||
h.opts.Logger.Error(ctx, "failed to read body", err)
|
|
||||||
}
|
|
||||||
return errors.InternalServerError("go.micro.client", string(buf))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// response like text/plain or something else, return original error
|
||||||
cf, cerr := h.newCodec(ct)
|
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||||
if cerr != nil {
|
} else 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", cerr.Error())
|
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.opts.Logger.V(logger.DebugLevel) {
|
|
||||||
h.opts.Logger.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header))
|
|
||||||
}
|
|
||||||
|
|
||||||
// succeseful response
|
// succeseful response
|
||||||
if hrsp.StatusCode < 400 {
|
if hrsp.StatusCode < 400 {
|
||||||
if err = cf.Unmarshal(buf, rsp); err != nil {
|
if err = cf.ReadBody(hrsp.Body, rsp); err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@ -319,10 +278,14 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !ok || rerr == nil {
|
if !ok || rerr == nil {
|
||||||
|
buf, rerr := io.ReadAll(hrsp.Body)
|
||||||
|
if rerr != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", rerr.Error())
|
||||||
|
}
|
||||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||||
}
|
}
|
||||||
|
|
||||||
if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
|
if cerr := cf.ReadBody(hrsp.Body, rerr); cerr != nil {
|
||||||
return errors.InternalServerError("go.micro.client", cerr.Error())
|
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -339,26 +302,3 @@ type tag struct {
|
|||||||
key string
|
key string
|
||||||
name string
|
name 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
|
|
||||||
}
|
|
||||||
|
38
util_test.go
38
util_test.go
@ -14,7 +14,7 @@ func TestParsing(t *testing.T) {
|
|||||||
|
|
||||||
for _, m := range []string{"POST"} {
|
for _, m := range []string{"POST"} {
|
||||||
body := ""
|
body := ""
|
||||||
path, nmsg, err := newPathRequest("/users/iin/{iin}/push-notifications", m, body, omsg, []string{"protobuf", "json"}, nil)
|
path, nmsg, err := newPathRequest("/users/iin/{iin}/push-notifications", m, body, omsg, []string{"protobuf", "json"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -44,7 +44,7 @@ func TestNewPathRequest(t *testing.T) {
|
|||||||
|
|
||||||
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
|
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
|
||||||
body := ""
|
body := ""
|
||||||
path, nmsg, err := newPathRequest("/v1/test", m, body, omsg, []string{"protobuf", "json"}, nil)
|
path, nmsg, err := newPathRequest("/v1/test", m, body, omsg, []string{"protobuf", "json"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -59,38 +59,6 @@ func TestNewPathRequest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewPathVarRequest(t *testing.T) {
|
func TestNewPathVarRequest(t *testing.T) {
|
||||||
type Message struct {
|
type Message struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@ -106,7 +74,7 @@ func TestNewPathVarRequest(t *testing.T) {
|
|||||||
if m != "GET" {
|
if m != "GET" {
|
||||||
body = "*"
|
body = "*"
|
||||||
}
|
}
|
||||||
path, nmsg, err := newPathRequest("/v1/test/{val1}", m, body, omsg, []string{"protobuf", "json"}, nil)
|
path, nmsg, err := newPathRequest("/v1/test/{val1}", m, body, omsg, []string{"protobuf", "json"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user