Compare commits
51 Commits
Author | SHA1 | Date | |
---|---|---|---|
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 |
19
.github/dependabot.yml
vendored
Normal file
19
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
|
||||||
|
# Maintain dependencies for GitHub Actions
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
|
||||||
|
# Maintain dependencies for Golang
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
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": [
|
|
||||||
"*"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
4
.github/workflows/build.yml
vendored
4
.github/workflows/build.yml
vendored
@@ -3,6 +3,7 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
@@ -34,9 +35,10 @@ jobs:
|
|||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v2
|
||||||
|
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.
|
||||||
version: v1.39
|
version: v1.30
|
||||||
# Optional: working directory, useful for monorepos
|
# Optional: working directory, useful for monorepos
|
||||||
# working-directory: somedir
|
# working-directory: somedir
|
||||||
# Optional: golangci-lint command line arguments.
|
# Optional: golangci-lint command line arguments.
|
||||||
|
78
.github/workflows/codeql-analysis.yml
vendored
Normal file
78
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# For most projects, this workflow file will not need changing; you simply need
|
||||||
|
# to commit it to your repository.
|
||||||
|
#
|
||||||
|
# You may wish to alter this file to override the set of languages analyzed,
|
||||||
|
# or to provide custom queries or build logic.
|
||||||
|
#
|
||||||
|
# ******** NOTE ********
|
||||||
|
# We have attempted to detect the languages in your repository. Please check
|
||||||
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
|
# supported CodeQL languages.
|
||||||
|
#
|
||||||
|
name: "codeql"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
push:
|
||||||
|
branches: [ master, v3 ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ master, v3 ]
|
||||||
|
schedule:
|
||||||
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'go' ]
|
||||||
|
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||||
|
# Learn more:
|
||||||
|
# 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:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.16
|
||||||
|
# Initializes the CodeQL tools for scanning.
|
||||||
|
- name: init
|
||||||
|
uses: github/codeql-action/init@v1
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
|
# By default, queries listed here will override any specified in a config file.
|
||||||
|
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||||
|
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
- name: autobuild
|
||||||
|
uses: github/codeql-action/autobuild@v1
|
||||||
|
|
||||||
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
|
# 📚 https://git.io/JvXDl
|
||||||
|
|
||||||
|
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||||
|
# and modify them (or add more) to build your code if your project
|
||||||
|
# uses a compiled language
|
||||||
|
|
||||||
|
#- run: |
|
||||||
|
# make bootstrap
|
||||||
|
# make release
|
||||||
|
|
||||||
|
- name: analyze
|
||||||
|
uses: github/codeql-action/analyze@v1
|
31
.github/workflows/dependabot-automerge.yml
vendored
Normal file
31
.github/workflows/dependabot-automerge.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
name: "prautomerge"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
dependabot:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: ${{ github.actor == 'dependabot[bot]' }}
|
||||||
|
steps:
|
||||||
|
- name: metadata
|
||||||
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v1.1.1
|
||||||
|
with:
|
||||||
|
github-token: "${{ secrets.TOKEN }}"
|
||||||
|
- name: approve
|
||||||
|
run: gh pr review --approve "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
|
- name: merge
|
||||||
|
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||||
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
4
.github/workflows/pr.yml
vendored
4
.github/workflows/pr.yml
vendored
@@ -3,6 +3,7 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
@@ -34,9 +35,10 @@ jobs:
|
|||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v2
|
||||||
|
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.
|
||||||
version: v1.39
|
version: v1.30
|
||||||
# Optional: working directory, useful for monorepos
|
# Optional: working directory, useful for monorepos
|
||||||
# working-directory: somedir
|
# working-directory: somedir
|
||||||
# Optional: golangci-lint command line arguments.
|
# Optional: golangci-lint command line arguments.
|
||||||
|
@@ -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/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
|
## Usage
|
||||||
|
|
||||||
### Use directly
|
### Use directly
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "github.com/unistack-org/micro-client-http"
|
import "go.unistack.org/micro-client-http/v3"
|
||||||
|
|
||||||
service := micro.NewService(
|
service := micro.NewService(
|
||||||
micro.Name("my.service"),
|
micro.Name("my.service"),
|
||||||
|
4
go.mod
4
go.mod
@@ -1,5 +1,5 @@
|
|||||||
module github.com/unistack-org/micro-client-http/v3
|
module go.unistack.org/micro-client-http/v3
|
||||||
|
|
||||||
go 1.16
|
go 1.16
|
||||||
|
|
||||||
require github.com/unistack-org/micro/v3 v3.4.8
|
require go.unistack.org/micro/v3 v3.8.12
|
||||||
|
23
go.sum
23
go.sum
@@ -1,17 +1,26 @@
|
|||||||
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/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
||||||
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
|
github.com/golang-jwt/jwt/v4 v4.1.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
|
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/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/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/silas/dag v0.0.0-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||||
github.com/unistack-org/micro/v3 v3.4.8 h1:9+qGlNHgChC3aMuFrtTFUtG55PEAjneSvplg7phwoCI=
|
go.unistack.org/micro-proto/v3 v3.1.0 h1:q39FwjFiRZn+Ux/tt+d3bJTmDtsQQWa+3SLYVo1vLfA=
|
||||||
github.com/unistack-org/micro/v3 v3.4.8/go.mod h1:LXmPfbJnJNvL0kQs8HfnkV3Wya2Wb+C7keVq++RCZnk=
|
go.unistack.org/micro-proto/v3 v3.1.0/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
|
||||||
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
go.unistack.org/micro/v3 v3.8.12 h1:ACaHE8ZIHFXqEGPSRvXzND4hcqCSQf04WkzOFY6Y1gQ=
|
||||||
|
go.unistack.org/micro/v3 v3.8.12/go.mod h1:KMMmOmbgo/D52/rCAbqeKbBsgEEbSKM69he54J3ZIuA=
|
||||||
|
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
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/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/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/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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/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/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.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
176
http.go
176
http.go
@@ -1,5 +1,5 @@
|
|||||||
// Package http provides a http client
|
// Package http provides a http client
|
||||||
package http
|
package http // import "go.unistack.org/micro-client-http/v3"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
@@ -15,11 +15,12 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/errors"
|
"go.unistack.org/micro/v3/errors"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
var DefaultContentType = "application/json"
|
var DefaultContentType = "application/json"
|
||||||
@@ -40,6 +41,7 @@ type httpClient struct {
|
|||||||
|
|
||||||
func newRequest(ctx context.Context, 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
|
||||||
@@ -55,6 +57,7 @@ func newRequest(ctx context.Context, addr string, req client.Request, ct string,
|
|||||||
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
|
||||||
@@ -68,6 +71,32 @@ func newRequest(ctx context.Context, addr string, req client.Request, ct string,
|
|||||||
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 {
|
||||||
@@ -85,38 +114,27 @@ func newRequest(ctx context.Context, addr string, req client.Request, ct string,
|
|||||||
|
|
||||||
u, err = u.Parse(path)
|
u, err = u.Parse(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client_v", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var nmsg interface{}
|
||||||
|
if len(u.Query()) > 0 {
|
||||||
|
path, nmsg, err = newPathRequest(u.Path+"?"+u.RawQuery, method, body, msg, tags, parameters)
|
||||||
|
} 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 {
|
||||||
return nil, errors.BadRequest("go.micro.client_a", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
u, err = url.Parse(fmt.Sprintf("%s://%s%s", scheme, host, path))
|
u, err = url.Parse(fmt.Sprintf("%s://%s%s", scheme, host, path))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client_t", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
}
|
|
||||||
|
|
||||||
b, err := cf.Marshal(nmsg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.BadRequest("go.micro.client_e", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
var hreq *http.Request
|
|
||||||
if len(b) > 0 {
|
|
||||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), ioutil.NopCloser(bytes.NewBuffer(b)))
|
|
||||||
hreq.ContentLength = int64(len(b))
|
|
||||||
} else {
|
|
||||||
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.BadRequest("go.micro.client_k", err.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var cookies []*http.Cookie
|
||||||
header := make(http.Header)
|
header := make(http.Header)
|
||||||
|
|
||||||
if opts.Context != nil {
|
if opts.Context != nil {
|
||||||
if md, ok := opts.Context.Value(metadataKey{}).(metadata.Metadata); ok {
|
if md, ok := opts.Context.Value(metadataKey{}).(metadata.Metadata); ok {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
@@ -124,27 +142,72 @@ func newRequest(ctx context.Context, addr string, req client.Request, ct string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.AuthToken != "" {
|
if opts.AuthToken != "" {
|
||||||
hreq.Header.Set("Authorization", opts.AuthToken)
|
header.Set(metadata.HeaderAuthorization, opts.AuthToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
hreq.Header.Set(k, v)
|
header.Set(k, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// set timeout in nanoseconds
|
// set timeout in nanoseconds
|
||||||
if opts.StreamTimeout > time.Duration(0) {
|
if opts.StreamTimeout > time.Duration(0) {
|
||||||
hreq.Header.Set("Timeout", fmt.Sprintf("%d", opts.StreamTimeout))
|
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.StreamTimeout))
|
||||||
}
|
}
|
||||||
if opts.RequestTimeout > time.Duration(0) {
|
if opts.RequestTimeout > time.Duration(0) {
|
||||||
hreq.Header.Set("Timeout", fmt.Sprintf("%d", opts.RequestTimeout))
|
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.RequestTimeout))
|
||||||
}
|
}
|
||||||
|
|
||||||
// set the content type for the request
|
// set the content type for the request
|
||||||
hreq.Header.Set("Content-Type", ct)
|
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)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var hreq *http.Request
|
||||||
|
if len(b) > 0 {
|
||||||
|
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), ioutil.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", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
hreq.Header = header
|
||||||
|
for _, cookie := range cookies {
|
||||||
|
hreq.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
|
||||||
return hreq, nil
|
return hreq, nil
|
||||||
}
|
}
|
||||||
@@ -532,15 +595,34 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
|||||||
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 {
|
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...)
|
options := client.NewPublishOptions(opts...)
|
||||||
|
|
||||||
md, ok := metadata.FromOutgoingContext(ctx)
|
// get proxy
|
||||||
if !ok {
|
exchange := ""
|
||||||
md = metadata.New(2)
|
if v, ok := os.LookupEnv("MICRO_PROXY"); ok {
|
||||||
|
exchange = v
|
||||||
}
|
}
|
||||||
md["Content-Type"] = p.ContentType()
|
|
||||||
md["Micro-Topic"] = p.Topic()
|
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())
|
cf, err := h.newCodec(p.ContentType())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -561,21 +643,15 @@ func (h *httpClient) Publish(ctx context.Context, p client.Message, opts ...clie
|
|||||||
}
|
}
|
||||||
|
|
||||||
topic := p.Topic()
|
topic := p.Topic()
|
||||||
|
if len(exchange) > 0 {
|
||||||
// get proxy
|
topic = exchange
|
||||||
if prx := os.Getenv("MICRO_PROXY"); len(prx) > 0 {
|
|
||||||
options.Exchange = prx
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// get the exchange
|
md.Set(metadata.HeaderTopic, topic)
|
||||||
if len(options.Exchange) > 0 {
|
msgs = append(msgs, &broker.Message{Header: md, Body: body})
|
||||||
topic = options.Exchange
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return h.opts.Broker.Publish(ctx, topic, &broker.Message{
|
return h.opts.Broker.BatchPublish(ctx, msgs,
|
||||||
Header: md,
|
|
||||||
Body: body,
|
|
||||||
},
|
|
||||||
broker.PublishContext(ctx),
|
broker.PublishContext(ctx),
|
||||||
broker.PublishBodyOnly(options.BodyOnly),
|
broker.PublishBodyOnly(options.BodyOnly),
|
||||||
)
|
)
|
||||||
|
51
http_test.go
51
http_test.go
@@ -8,14 +8,56 @@ import (
|
|||||||
|
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Field1 string
|
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) {
|
||||||
|
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) {
|
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)
|
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -32,9 +74,8 @@ 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}
|
||||||
p, m, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil)
|
_, _, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil, nil)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatalf("path param must not be filled")
|
t.Fatal("path param must not be filled")
|
||||||
}
|
}
|
||||||
_, _ = p, m
|
|
||||||
}
|
}
|
||||||
|
16
message.go
16
message.go
@@ -1,25 +1,29 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpMessage struct {
|
type httpMessage struct {
|
||||||
payload interface{}
|
payload interface{}
|
||||||
topic string
|
topic string
|
||||||
contentType string
|
contentType string
|
||||||
|
opts client.MessageOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
func newHTTPMessage(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
|
func newHTTPMessage(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
|
||||||
options := client.NewMessageOptions(opts...)
|
options := client.NewMessageOptions(opts...)
|
||||||
if len(options.ContentType) == 0 {
|
|
||||||
options.ContentType = contentType
|
if len(options.ContentType) > 0 {
|
||||||
|
contentType = options.ContentType
|
||||||
}
|
}
|
||||||
|
|
||||||
return &httpMessage{
|
return &httpMessage{
|
||||||
payload: payload,
|
payload: payload,
|
||||||
topic: topic,
|
topic: topic,
|
||||||
contentType: options.ContentType,
|
contentType: contentType,
|
||||||
|
opts: options,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,3 +38,7 @@ func (h *httpMessage) Topic() string {
|
|||||||
func (h *httpMessage) Payload() interface{} {
|
func (h *httpMessage) Payload() interface{} {
|
||||||
return h.payload
|
return h.payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *httpMessage) Metadata() metadata.Metadata {
|
||||||
|
return h.opts.Metadata
|
||||||
|
}
|
||||||
|
25
options.go
25
options.go
@@ -4,8 +4,8 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -57,6 +57,7 @@ func MaxSendMsgSize(s int) client.Option {
|
|||||||
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) client.Option {
|
||||||
return client.SetOption(httpClientKey{}, c)
|
return client.SetOption(httpClientKey{}, c)
|
||||||
}
|
}
|
||||||
@@ -64,24 +65,28 @@ func HTTPClient(c *http.Client) client.Option {
|
|||||||
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) client.Option {
|
||||||
return client.SetOption(httpDialerKey{}, d)
|
return client.SetOption(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) client.CallOption {
|
||||||
return client.SetCallOption(methodKey{}, m)
|
return client.SetCallOption(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) client.CallOption {
|
||||||
return client.SetCallOption(pathKey{}, p)
|
return client.SetCallOption(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) client.CallOption {
|
||||||
return client.SetCallOption(bodyKey{}, b)
|
return client.SetCallOption(bodyKey{}, b)
|
||||||
}
|
}
|
||||||
@@ -94,12 +99,28 @@ func ErrorMap(m map[string]interface{}) client.CallOption {
|
|||||||
|
|
||||||
type structTagsKey struct{}
|
type structTagsKey struct{}
|
||||||
|
|
||||||
|
// StructTags pass tags slice option to client Call
|
||||||
func StructTags(tags []string) client.CallOption {
|
func StructTags(tags []string) client.CallOption {
|
||||||
return client.SetCallOption(structTagsKey{}, tags)
|
return client.SetCallOption(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) client.CallOption {
|
||||||
return client.SetCallOption(metadataKey{}, md)
|
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
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpRequest struct {
|
type httpRequest struct {
|
||||||
|
@@ -9,9 +9,9 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/errors"
|
"go.unistack.org/micro/v3/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Implements the streamer interface
|
// Implements the streamer interface
|
||||||
|
110
util.go
110
util.go
@@ -10,14 +10,14 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
"github.com/unistack-org/micro/v3/errors"
|
"go.unistack.org/micro/v3/errors"
|
||||||
rutil "github.com/unistack-org/micro/v3/util/reflect"
|
"go.unistack.org/micro/v3/logger"
|
||||||
util "github.com/unistack-org/micro/v3/util/router"
|
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
templateCache = make(map[string]util.Template)
|
templateCache = make(map[string][]string)
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -38,21 +38,34 @@ func GetError(err error) interface{} {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPathRequest(path string, method string, body string, msg interface{}, tags []string) (string, interface{}, error) {
|
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
|
// 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 {
|
||||||
return "", nil, err
|
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)
|
return "", nil, fmt.Errorf("nil message but path params requested: %v", path)
|
||||||
}
|
}
|
||||||
|
|
||||||
fieldsmapskip := make(map[string]struct{})
|
fieldsmapskip := make(map[string]struct{})
|
||||||
fieldsmap := make(map[string]string, len(tpl.Fields))
|
fieldsmap := make(map[string]string, len(tpl))
|
||||||
for _, v := range tpl.Fields {
|
for _, v := range tpl {
|
||||||
fieldsmap[v] = ""
|
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)
|
nmsg, err := rutil.Zero(msg)
|
||||||
@@ -104,16 +117,24 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.name == "" {
|
cname := 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint: gocritic
|
// nolint: gocritic, nestif
|
||||||
if _, ok := fieldsmap[t.name]; ok {
|
if _, ok := fieldsmap[t.name]; ok {
|
||||||
switch val.Type().Kind() {
|
switch val.Type().Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
@@ -124,8 +145,10 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
default:
|
default:
|
||||||
fieldsmap[t.name] = fmt.Sprintf("%v", val.Interface())
|
fieldsmap[t.name] = fmt.Sprintf("%v", val.Interface())
|
||||||
}
|
}
|
||||||
} else if (body == "*" || body == t.name) && method != http.MethodGet && tnmsg.Field(i).CanSet() {
|
} else if (body == "*" || body == t.name) && method != http.MethodGet {
|
||||||
|
if tnmsg.Field(i).CanSet() {
|
||||||
tnmsg.Field(i).Set(val)
|
tnmsg.Field(i).Set(val)
|
||||||
|
}
|
||||||
} 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++ {
|
||||||
@@ -146,15 +169,38 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
}
|
}
|
||||||
|
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
for _, fld := range tpl.Pool {
|
|
||||||
|
for _, fld := range tpl {
|
||||||
_, _ = b.WriteRune('/')
|
_, _ = b.WriteRune('/')
|
||||||
if v, ok := fieldsmap[fld]; ok {
|
// nolint: nestif
|
||||||
if v != "" {
|
var vs, ve, vf int
|
||||||
_, _ = b.WriteString(v)
|
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 {
|
} else {
|
||||||
_, _ = b.WriteString(fld)
|
_, _ = b.WriteString(fld)
|
||||||
}
|
}
|
||||||
|
vs = 0
|
||||||
|
ve = 0
|
||||||
|
pholder = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !pholder {
|
||||||
|
_, _ = b.WriteString(fld)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(values) > 0 {
|
if len(values) > 0 {
|
||||||
@@ -162,6 +208,12 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
_, _ = b.WriteString(values.Encode())
|
_, _ = b.WriteString(values.Encode())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
if err = rutil.ZeroFieldByPath(nmsg, k); err != nil {
|
||||||
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
if rutil.IsZero(nmsg) {
|
if rutil.IsZero(nmsg) {
|
||||||
return b.String(), nil, nil
|
return b.String(), nil, nil
|
||||||
}
|
}
|
||||||
@@ -169,7 +221,10 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
|
|||||||
return b.String(), nmsg, nil
|
return b.String(), nmsg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTemplate(path string) (util.Template, error) {
|
func newTemplate(path string) ([]string, error) {
|
||||||
|
if len(path) == 0 || path[0] != '/' {
|
||||||
|
return nil, fmt.Errorf("path must starts with /")
|
||||||
|
}
|
||||||
mu.RLock()
|
mu.RLock()
|
||||||
tpl, ok := templateCache[path]
|
tpl, ok := templateCache[path]
|
||||||
if ok {
|
if ok {
|
||||||
@@ -178,12 +233,7 @@ func newTemplate(path string) (util.Template, error) {
|
|||||||
}
|
}
|
||||||
mu.RUnlock()
|
mu.RUnlock()
|
||||||
|
|
||||||
rule, err := util.Parse(path)
|
tpl = strings.Split(path[1:], "/")
|
||||||
if err != nil {
|
|
||||||
return tpl, err
|
|
||||||
}
|
|
||||||
|
|
||||||
tpl = rule.Compile()
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
templateCache[path] = tpl
|
templateCache[path] = tpl
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
@@ -209,7 +259,17 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
|
|||||||
}
|
}
|
||||||
|
|
||||||
cf, cerr := h.newCodec(ct)
|
cf, cerr := h.newCodec(ct)
|
||||||
if cerr != nil {
|
if hrsp.StatusCode >= 400 && cerr != nil {
|
||||||
|
var buf []byte
|
||||||
|
if hrsp.Body != nil {
|
||||||
|
buf, err = io.ReadAll(hrsp.Body)
|
||||||
|
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
|
h.opts.Logger.Errorf(ctx, "failed to read body: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// response like text/plain or something else, return original error
|
||||||
|
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
||||||
|
} else if cerr != nil {
|
||||||
return errors.InternalServerError("go.micro.client", cerr.Error())
|
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
30
util_test.go
30
util_test.go
@@ -5,13 +5,31 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestTemplate(t *testing.T) {
|
func TestParsing(t *testing.T) {
|
||||||
tpl, err := newTemplate("/v1/{ClientID}/list")
|
type Message struct {
|
||||||
|
IIN string `protobuf:"bytes,1,opt,name=iin,proto3" json:"iin"`
|
||||||
|
}
|
||||||
|
|
||||||
|
omsg := &Message{IIN: "5555"}
|
||||||
|
|
||||||
|
for _, m := range []string{"POST"} {
|
||||||
|
body := ""
|
||||||
|
path, nmsg, err := newPathRequest("/users/iin/{iin}/push-notifications", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
_ = tpl
|
u, err := url.Parse(path)
|
||||||
// fmt.Printf("%#+v\n", tpl.Pool)
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = 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) {
|
func TestNewPathRequest(t *testing.T) {
|
||||||
@@ -26,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"})
|
path, nmsg, err := newPathRequest("/v1/test", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -56,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"})
|
path, nmsg, err := newPathRequest("/v1/test/{val1}", m, body, omsg, []string{"protobuf", "json"}, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user