Compare commits
34 Commits
Author | SHA1 | Date | |
---|---|---|---|
3592052ac9 | |||
fd5479f6e7 | |||
4fe11b430e | |||
5dc57579c3 | |||
|
f974460ff3 | ||
5c54b82aaf | |||
a5bf3e2edc | |||
3a2bac8723 | |||
|
9a72dba9df | ||
00e853e3ee | |||
5aff0014bb | |||
807b4dc41a | |||
a1f432fac9 | |||
dd7e872858 | |||
57c2a5b95f | |||
73fc3d34f0 | |||
09e7282b2b | |||
5f029fd432 | |||
8555ebdd5c | |||
273da35b92 | |||
556e8dd568 | |||
f3573e651b | |||
8074f9f617 | |||
e497b5fa89 | |||
520dc29f89 | |||
59d6c26003 | |||
fade40754a | |||
f39d449ca2 | |||
7cab3c18a7 | |||
7098c252dc | |||
3cbc879769 | |||
05add422d1 | |||
|
b4970ee807 | ||
|
f4c91686f4 |
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": [
|
|
||||||
"*"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
13
.github/stale.sh
vendored
13
.github/stale.sh
vendored
@@ -1,13 +0,0 @@
|
|||||||
#!/bin/bash -ex
|
|
||||||
|
|
||||||
export PATH=$PATH:$(pwd)/bin
|
|
||||||
export GO111MODULE=on
|
|
||||||
export GOBIN=$(pwd)/bin
|
|
||||||
|
|
||||||
#go get github.com/rvflash/goup@v0.4.1
|
|
||||||
|
|
||||||
#goup -v ./...
|
|
||||||
#go get github.com/psampaz/go-mod-outdated@v0.6.0
|
|
||||||
go list -u -m -mod=mod -json all | go-mod-outdated -update -direct -ci || true
|
|
||||||
|
|
||||||
#go list -u -m -json all | go-mod-outdated -update
|
|
75
.github/workflows/codeql-analysis.yml
vendored
Normal file
75
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
# 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 ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ master ]
|
||||||
|
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 repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
# Initializes the CodeQL tools for scanning.
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
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: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v1
|
66
.github/workflows/dependabot-automerge.yml
vendored
Normal file
66
.github/workflows/dependabot-automerge.yml
vendored
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
name: "prautomerge"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Dependabot-Automerge:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
# 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:
|
||||||
|
- name: Approve Changes and Merge changes if label 'dependencies' is set
|
||||||
|
uses: actions/github-script@v4
|
||||||
|
with:
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
script: |
|
||||||
|
console.log(context.payload.workflow_run);
|
||||||
|
|
||||||
|
var labelNames = await github.paginate(
|
||||||
|
github.issues.listLabelsOnIssue,
|
||||||
|
{
|
||||||
|
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');
|
||||||
|
}
|
44
.golangci.yml
Normal file
44
.golangci.yml
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
run:
|
||||||
|
concurrency: 4
|
||||||
|
deadline: 5m
|
||||||
|
issues-exit-code: 1
|
||||||
|
tests: true
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
govet:
|
||||||
|
check-shadowing: true
|
||||||
|
enable:
|
||||||
|
- fieldalignment
|
||||||
|
|
||||||
|
linters:
|
||||||
|
enable:
|
||||||
|
- govet
|
||||||
|
- deadcode
|
||||||
|
- errcheck
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- staticcheck
|
||||||
|
- structcheck
|
||||||
|
- typecheck
|
||||||
|
- unused
|
||||||
|
- varcheck
|
||||||
|
- bodyclose
|
||||||
|
- gci
|
||||||
|
- goconst
|
||||||
|
- gocritic
|
||||||
|
- gosimple
|
||||||
|
- gofmt
|
||||||
|
- gofumpt
|
||||||
|
- goimports
|
||||||
|
- golint
|
||||||
|
- gosec
|
||||||
|
- makezero
|
||||||
|
- misspell
|
||||||
|
- nakedret
|
||||||
|
- nestif
|
||||||
|
- nilerr
|
||||||
|
- noctx
|
||||||
|
- prealloc
|
||||||
|
- unconvert
|
||||||
|
- unparam
|
||||||
|
disable-all: false
|
@@ -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.3.14
|
require go.unistack.org/micro/v3 v3.8.4
|
||||||
|
25
go.sum
25
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.3.14 h1:CAkDMjHZT8/D6GGF5h3gK84m6tlWZC17IGPb2GkAn/4=
|
go.unistack.org/micro-proto/v3 v3.1.0 h1:q39FwjFiRZn+Ux/tt+d3bJTmDtsQQWa+3SLYVo1vLfA=
|
||||||
github.com/unistack-org/micro/v3 v3.3.14/go.mod h1:ETGcQQUcjxGaD44LUMX+0fgo8Loh7ExldfIPLvfUmDo=
|
go.unistack.org/micro-proto/v3 v3.1.0/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
|
||||||
golang.org/x/net v0.0.0-20210415231046-e915ea6b2b7d/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
|
go.unistack.org/micro/v3 v3.8.4 h1:Nny6JT7TlDS0e5bPVmbbpKXrisMQ6q9cvao5uyaa3eo=
|
||||||
|
go.unistack.org/micro/v3 v3.8.4/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-20210330210617-4fbd30eecc44/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=
|
||||||
|
371
http.go
371
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,66 +15,87 @@ 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"
|
||||||
"github.com/unistack-org/micro/v3/router"
|
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var DefaultContentType = "application/json"
|
||||||
DefaultContentType = "application/json"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
/*
|
||||||
func filterLabel(r []router.Route) []router.Route {
|
func filterLabel(r []router.Route) []router.Route {
|
||||||
// selector.FilterLabel("protocol", "http")
|
// selector.FilterLabel("protocol", "http")
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
type httpClient struct {
|
type httpClient struct {
|
||||||
opts client.Options
|
|
||||||
dialer *net.Dialer
|
|
||||||
httpcli *http.Client
|
httpcli *http.Client
|
||||||
init bool
|
opts client.Options
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
|
init bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRequest(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) {
|
||||||
hreq := &http.Request{Method: http.MethodPost}
|
|
||||||
body := "*" // as like google api http annotation
|
|
||||||
|
|
||||||
var tags []string
|
var tags []string
|
||||||
var scheme string
|
var parameters map[string]map[string]string
|
||||||
u, err := url.Parse(addr)
|
scheme := "http"
|
||||||
if err != nil {
|
method := http.MethodPost
|
||||||
hreq.URL = &url.URL{
|
body := "*" // as like google api http annotation
|
||||||
Scheme: "http",
|
host := addr
|
||||||
Host: addr,
|
path := req.Endpoint()
|
||||||
Path: req.Endpoint(),
|
|
||||||
}
|
|
||||||
hreq.Host = addr
|
|
||||||
scheme = "http"
|
|
||||||
} else {
|
|
||||||
ep := req.Endpoint()
|
|
||||||
if opts.Context != nil {
|
|
||||||
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
|
||||||
hreq.Method = m
|
|
||||||
}
|
|
||||||
if p, ok := opts.Context.Value(pathKey{}).(string); ok {
|
|
||||||
ep = p
|
|
||||||
}
|
|
||||||
if b, ok := opts.Context.Value(bodyKey{}).(string); ok {
|
|
||||||
body = b
|
|
||||||
}
|
|
||||||
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
|
||||||
tags = t
|
|
||||||
}
|
|
||||||
|
|
||||||
|
u, err := url.Parse(addr)
|
||||||
|
if err == nil {
|
||||||
|
scheme = u.Scheme
|
||||||
|
path = u.Path
|
||||||
|
host = u.Host
|
||||||
|
} else {
|
||||||
|
u = &url.URL{Scheme: scheme, Path: path, Host: host}
|
||||||
|
}
|
||||||
|
|
||||||
|
// nolint: nestif
|
||||||
|
if opts.Context != nil {
|
||||||
|
if m, ok := opts.Context.Value(methodKey{}).(string); ok {
|
||||||
|
method = m
|
||||||
}
|
}
|
||||||
hreq.URL, err = u.Parse(ep)
|
if p, ok := opts.Context.Value(pathKey{}).(string); ok {
|
||||||
if err != nil {
|
path += p
|
||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
}
|
||||||
|
if b, ok := opts.Context.Value(bodyKey{}).(string); ok {
|
||||||
|
body = b
|
||||||
|
}
|
||||||
|
if t, ok := opts.Context.Value(structTagsKey{}).([]string); ok && len(t) > 0 {
|
||||||
|
tags = t
|
||||||
|
}
|
||||||
|
if k, ok := opts.Context.Value(headerKey{}).([]string); ok && len(k) > 0 {
|
||||||
|
if parameters == nil {
|
||||||
|
parameters = make(map[string]map[string]string)
|
||||||
|
}
|
||||||
|
m, ok := parameters["header"]
|
||||||
|
if !ok {
|
||||||
|
m = make(map[string]string)
|
||||||
|
parameters["header"] = m
|
||||||
|
}
|
||||||
|
for idx := 0; idx < len(k)/2; idx += 2 {
|
||||||
|
m[k[idx]] = k[idx+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if k, ok := opts.Context.Value(cookieKey{}).([]string); ok && len(k) > 0 {
|
||||||
|
if parameters == nil {
|
||||||
|
parameters = make(map[string]map[string]string)
|
||||||
|
}
|
||||||
|
m, ok := parameters["cookie"]
|
||||||
|
if !ok {
|
||||||
|
m = make(map[string]string)
|
||||||
|
parameters["cookie"] = m
|
||||||
|
}
|
||||||
|
for idx := 0; idx < len(k)/2; idx += 2 {
|
||||||
|
m[k[idx]] = k[idx+1]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,122 +108,158 @@ func newRequest(addr string, req client.Request, ct string, cf codec.Codec, msg
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
path, nmsg, err := newPathRequest(hreq.URL.Path, hreq.Method, body, msg, tags)
|
if path == "" {
|
||||||
|
path = req.Endpoint()
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err = u.Parse(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if scheme != "" {
|
var nmsg interface{}
|
||||||
hreq.URL, err = url.Parse(scheme + "://" + addr + path)
|
if len(u.Query()) > 0 {
|
||||||
|
path, nmsg, err = newPathRequest(u.Path+"?"+u.RawQuery, method, body, msg, tags, parameters)
|
||||||
} else {
|
} else {
|
||||||
hreq.URL, err = url.Parse(addr + path)
|
path, nmsg, err = newPathRequest(u.Path, method, body, msg, tags, parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.BadRequest("go.micro.client", err.Error())
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
u, err = url.Parse(fmt.Sprintf("%s://%s%s", scheme, host, path))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.BadRequest("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var cookies []*http.Cookie
|
||||||
|
header := make(http.Header)
|
||||||
|
if opts.Context != nil {
|
||||||
|
if md, ok := opts.Context.Value(metadataKey{}).(metadata.Metadata); ok {
|
||||||
|
for k, v := range md {
|
||||||
|
header.Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if opts.AuthToken != "" {
|
||||||
|
header.Set(metadata.HeaderAuthorization, opts.AuthToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
|
for k, v := range md {
|
||||||
|
header.Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// set timeout in nanoseconds
|
||||||
|
if opts.StreamTimeout > time.Duration(0) {
|
||||||
|
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.StreamTimeout))
|
||||||
|
}
|
||||||
|
if opts.RequestTimeout > time.Duration(0) {
|
||||||
|
header.Set(metadata.HeaderTimeout, fmt.Sprintf("%d", opts.RequestTimeout))
|
||||||
|
}
|
||||||
|
|
||||||
|
// set the content type for the request
|
||||||
|
header.Set(metadata.HeaderContentType, ct)
|
||||||
|
var v interface{}
|
||||||
|
|
||||||
|
for km, vm := range parameters {
|
||||||
|
for k, required := range vm {
|
||||||
|
v, err = rutil.StructFieldByPath(nmsg, 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())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var hreq *http.Request
|
||||||
if len(b) > 0 {
|
if len(b) > 0 {
|
||||||
hreq.Body = 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 {
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) call(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
func (h *httpClient) call(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||||
header := make(http.Header, 2)
|
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
|
||||||
for k, v := range md {
|
|
||||||
header.Set(k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := req.ContentType()
|
ct := req.ContentType()
|
||||||
if len(opts.ContentType) > 0 {
|
if len(opts.ContentType) > 0 {
|
||||||
ct = opts.ContentType
|
ct = opts.ContentType
|
||||||
}
|
}
|
||||||
|
|
||||||
// set timeout in nanoseconds
|
|
||||||
header.Set("Timeout", fmt.Sprintf("%d", opts.RequestTimeout))
|
|
||||||
// set the content type for the request
|
|
||||||
header.Set("Content-Type", ct)
|
|
||||||
|
|
||||||
cf, err := h.newCodec(ct)
|
cf, err := h.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
hreq, err := newRequest(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
|
||||||
}
|
}
|
||||||
|
|
||||||
hreq.Header = header
|
|
||||||
|
|
||||||
// make the request
|
// make the request
|
||||||
hrsp, err := h.httpcli.Do(hreq.WithContext(ctx))
|
hrsp, err := h.httpcli.Do(hreq)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch err := err.(type) {
|
switch err := err.(type) {
|
||||||
case net.Error:
|
|
||||||
if err.Timeout() {
|
|
||||||
return errors.Timeout("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
case *url.Error:
|
case *url.Error:
|
||||||
if err, ok := err.Err.(net.Error); ok && err.Timeout() {
|
if err, ok := err.Err.(net.Error); ok && err.Timeout() {
|
||||||
return errors.Timeout("go.micro.client", err.Error())
|
return errors.Timeout("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
case net.Error:
|
||||||
|
if err.Timeout() {
|
||||||
|
return errors.Timeout("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
defer hrsp.Body.Close()
|
defer hrsp.Body.Close()
|
||||||
|
|
||||||
if ct == "application/x-www-form-urlencoded" {
|
|
||||||
cf, err = h.newCodec(DefaultContentType)
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h.parseRsp(ctx, hrsp, rsp, opts)
|
return h.parseRsp(ctx, hrsp, rsp, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) stream(ctx context.Context, addr string, req client.Request, opts client.CallOptions) (client.Stream, error) {
|
func (h *httpClient) stream(ctx context.Context, addr string, req client.Request, opts client.CallOptions) (client.Stream, error) {
|
||||||
var header http.Header
|
|
||||||
|
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
|
||||||
header = make(http.Header, len(md)+2)
|
|
||||||
for k, v := range md {
|
|
||||||
header.Set(k, v)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
header = make(http.Header, 2)
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := req.ContentType()
|
ct := req.ContentType()
|
||||||
if len(opts.ContentType) > 0 {
|
if len(opts.ContentType) > 0 {
|
||||||
ct = opts.ContentType
|
ct = opts.ContentType
|
||||||
}
|
}
|
||||||
|
|
||||||
// set timeout in nanoseconds
|
|
||||||
header.Set("Timeout", fmt.Sprintf("%d", opts.RequestTimeout))
|
|
||||||
// set the content type for the request
|
|
||||||
header.Set("Content-Type", ct)
|
|
||||||
|
|
||||||
// get codec
|
// get codec
|
||||||
cf, err := h.newCodec(ct)
|
cf, err := h.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
dialAddr := addr
|
|
||||||
u, err := url.Parse(dialAddr)
|
|
||||||
if err == nil && u.Scheme != "" && u.Host != "" {
|
|
||||||
dialAddr = u.Host
|
|
||||||
}
|
|
||||||
cc, err := (h.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
cc, err := (h.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error dialing: %v", err))
|
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error dialing: %v", err))
|
||||||
@@ -216,7 +273,6 @@ func (h *httpClient) stream(ctx context.Context, addr string, req client.Request
|
|||||||
conn: cc,
|
conn: cc,
|
||||||
ct: ct,
|
ct: ct,
|
||||||
cf: cf,
|
cf: cf,
|
||||||
header: header,
|
|
||||||
reader: bufio.NewReader(cc),
|
reader: bufio.NewReader(cc),
|
||||||
request: req,
|
request: req,
|
||||||
}, nil
|
}, nil
|
||||||
@@ -296,7 +352,7 @@ 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
|
||||||
opt := client.WithRequestTimeout(d.Sub(time.Now()))
|
opt := client.WithRequestTimeout(time.Until(d))
|
||||||
opt(&callOpts)
|
opt(&callOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,22 +465,22 @@ func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface
|
|||||||
func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, 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 _, o := range opts {
|
||||||
opt(&callOpts)
|
o(&callOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if we already have a deadline
|
// check if we already have a deadline
|
||||||
d, ok := ctx.Deadline()
|
d, ok := ctx.Deadline()
|
||||||
if !ok {
|
if !ok && callOpts.StreamTimeout > time.Duration(0) {
|
||||||
var cancel context.CancelFunc
|
var cancel context.CancelFunc
|
||||||
// no deadline so we create a new one
|
// no deadline so we create a new one
|
||||||
ctx, cancel = context.WithTimeout(ctx, callOpts.RequestTimeout)
|
ctx, cancel = context.WithTimeout(ctx, callOpts.StreamTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
} 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
|
||||||
opt := client.WithRequestTimeout(d.Sub(time.Now()))
|
o := client.WithStreamTimeout(time.Until(d))
|
||||||
opt(&callOpts)
|
o(&callOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
// should we noop right here?
|
// should we noop right here?
|
||||||
@@ -436,10 +492,7 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
// make copy of call method
|
// make copy of call method
|
||||||
hstream, err := h.stream()
|
hstream := h.stream
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
// 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-- {
|
||||||
hstream = callOpts.CallWrappers[i-1](hstream)
|
hstream = callOpts.CallWrappers[i-1](hstream)
|
||||||
@@ -476,9 +529,9 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
|||||||
|
|
||||||
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
|
||||||
t, err := callOpts.Backoff(ctx, req, i)
|
t, cerr := callOpts.Backoff(ctx, req, i)
|
||||||
if err != nil {
|
if cerr != nil {
|
||||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
return nil, errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
// only sleep if greater than 0
|
// only sleep if greater than 0
|
||||||
@@ -488,19 +541,19 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
|||||||
|
|
||||||
node := next()
|
node := next()
|
||||||
|
|
||||||
stream, err := h.stream(ctx, node, req, callOpts)
|
stream, cerr := h.stream(ctx, node, req, callOpts)
|
||||||
|
|
||||||
// record the result of the call to inform future routing decisions
|
// record the result of the call to inform future routing decisions
|
||||||
if verr := h.opts.Selector.Record(node, err); verr != nil {
|
if verr := h.opts.Selector.Record(node, cerr); verr != nil {
|
||||||
return nil, verr
|
return nil, verr
|
||||||
}
|
}
|
||||||
|
|
||||||
// try and transform the error to a go-micro error
|
// try and transform the error to a go-micro error
|
||||||
if verr, ok := err.(*errors.Error); ok {
|
if verr, ok := cerr.(*errors.Error); ok {
|
||||||
return nil, verr
|
return nil, verr
|
||||||
}
|
}
|
||||||
|
|
||||||
return stream, err
|
return stream, cerr
|
||||||
}
|
}
|
||||||
|
|
||||||
type response struct {
|
type response struct {
|
||||||
@@ -513,8 +566,8 @@ func (h *httpClient) Stream(ctx context.Context, req client.Request, opts ...cli
|
|||||||
|
|
||||||
for i := 0; i <= callOpts.Retries; i++ {
|
for i := 0; i <= callOpts.Retries; i++ {
|
||||||
go func() {
|
go func() {
|
||||||
s, err := call(i)
|
s, cerr := call(i)
|
||||||
ch <- response{s, err}
|
ch <- response{s, cerr}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
select {
|
select {
|
||||||
@@ -542,50 +595,66 @@ 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
|
||||||
|
exchange := ""
|
||||||
|
if v, ok := os.LookupEnv("MICRO_PROXY"); ok {
|
||||||
|
exchange = v
|
||||||
|
}
|
||||||
|
|
||||||
|
omd, ok := metadata.FromOutgoingContext(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
md = metadata.New(2)
|
omd = metadata.New(2)
|
||||||
}
|
|
||||||
md["Content-Type"] = p.ContentType()
|
|
||||||
md["Micro-Topic"] = p.Topic()
|
|
||||||
|
|
||||||
cf, err := h.newCodec(p.ContentType())
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var body []byte
|
msgs := make([]*broker.Message, 0, len(ps))
|
||||||
|
|
||||||
// passed in raw data
|
for _, p := range ps {
|
||||||
if d, ok := p.Payload().(*codec.Frame); ok {
|
md := metadata.Copy(omd)
|
||||||
body = d.Data
|
md[metadata.HeaderContentType] = p.ContentType()
|
||||||
} else {
|
md[metadata.HeaderTopic] = p.Topic()
|
||||||
b := bytes.NewBuffer(nil)
|
|
||||||
if err := cf.Write(b, &codec.Message{Type: codec.Event}, p.Payload()); err != nil {
|
cf, err := h.newCodec(p.ContentType())
|
||||||
|
if err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
}
|
}
|
||||||
body = b.Bytes()
|
|
||||||
|
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})
|
||||||
}
|
}
|
||||||
|
|
||||||
topic := p.Topic()
|
return h.opts.Broker.BatchPublish(ctx, msgs,
|
||||||
|
broker.PublishContext(ctx),
|
||||||
// get proxy
|
broker.PublishBodyOnly(options.BodyOnly),
|
||||||
if prx := os.Getenv("MICRO_PROXY"); len(prx) > 0 {
|
)
|
||||||
options.Exchange = prx
|
|
||||||
}
|
|
||||||
|
|
||||||
// get the exchange
|
|
||||||
if len(options.Exchange) > 0 {
|
|
||||||
topic = options.Exchange
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.opts.Broker.Publish(ctx, topic, &broker.Message{
|
|
||||||
Header: md,
|
|
||||||
Body: body,
|
|
||||||
}, broker.PublishContext(ctx))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpClient) String() string {
|
func (h *httpClient) String() string {
|
||||||
|
57
http_test.go
57
http_test.go
@@ -7,15 +7,57 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Field1 string
|
Field1 string `json:"field1"`
|
||||||
Field2 string
|
ClientID string
|
||||||
Field3 int64
|
Field2 string
|
||||||
|
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
|
|
||||||
}
|
}
|
||||||
|
@@ -1,13 +1,13 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpMessage struct {
|
type httpMessage struct {
|
||||||
|
payload interface{}
|
||||||
topic string
|
topic string
|
||||||
contentType string
|
contentType string
|
||||||
payload interface{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
|
43
options.go
43
options.go
@@ -4,7 +4,8 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -26,27 +27,28 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type poolMaxStreams struct{}
|
type poolMaxStreams struct{}
|
||||||
type poolMaxIdle struct{}
|
|
||||||
type codecsKey struct{}
|
|
||||||
type tlsAuth struct{}
|
|
||||||
type maxRecvMsgSizeKey struct{}
|
|
||||||
type maxSendMsgSizeKey struct{}
|
|
||||||
|
|
||||||
// PoolMaxStreams maximum streams on a connectioin
|
// PoolMaxStreams maximum streams on a connectioin
|
||||||
func PoolMaxStreams(n int) client.Option {
|
func PoolMaxStreams(n int) client.Option {
|
||||||
return client.SetOption(poolMaxStreams{}, n)
|
return client.SetOption(poolMaxStreams{}, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type poolMaxIdle struct{}
|
||||||
|
|
||||||
// PoolMaxIdle maximum idle conns of a pool
|
// PoolMaxIdle maximum idle conns of a pool
|
||||||
func PoolMaxIdle(d int) client.Option {
|
func PoolMaxIdle(d int) client.Option {
|
||||||
return client.SetOption(poolMaxIdle{}, d)
|
return client.SetOption(poolMaxIdle{}, d)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) client.Option {
|
func MaxRecvMsgSize(s int) client.Option {
|
||||||
return client.SetOption(maxRecvMsgSizeKey{}, s)
|
return client.SetOption(maxRecvMsgSizeKey{}, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) client.Option {
|
func MaxSendMsgSize(s int) client.Option {
|
||||||
return client.SetOption(maxSendMsgSizeKey{}, s)
|
return client.SetOption(maxSendMsgSizeKey{}, s)
|
||||||
@@ -54,30 +56,37 @@ func MaxSendMsgSize(s int) client.Option {
|
|||||||
|
|
||||||
type httpClientKey struct{}
|
type httpClientKey struct{}
|
||||||
|
|
||||||
|
// 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
type httpDialerKey struct{}
|
type httpDialerKey struct{}
|
||||||
|
|
||||||
|
// 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)
|
||||||
}
|
}
|
||||||
@@ -90,6 +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{}
|
||||||
|
|
||||||
|
// Metadata pass metadata to client Call
|
||||||
|
func Metadata(md metadata.Metadata) client.CallOption {
|
||||||
|
return client.SetCallOption(metadataKey{}, md)
|
||||||
|
}
|
||||||
|
|
||||||
|
type cookieKey struct{}
|
||||||
|
|
||||||
|
// Cookie pass cookie to client Call
|
||||||
|
func Cookie(cookies ...string) client.CallOption {
|
||||||
|
return client.SetCallOption(cookieKey{}, cookies)
|
||||||
|
}
|
||||||
|
|
||||||
|
type headerKey struct{}
|
||||||
|
|
||||||
|
// Header pass cookie to client Call
|
||||||
|
func Header(headers ...string) client.CallOption {
|
||||||
|
return client.SetCallOption(headerKey{}, headers)
|
||||||
|
}
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package http
|
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 {
|
||||||
|
85
stream.go
85
stream.go
@@ -9,31 +9,27 @@ 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
|
||||||
type httpStream struct {
|
type httpStream struct {
|
||||||
sync.RWMutex
|
|
||||||
address string
|
|
||||||
opts client.CallOptions
|
|
||||||
ct string
|
|
||||||
cf codec.Codec
|
|
||||||
context context.Context
|
|
||||||
header http.Header
|
|
||||||
seq uint64
|
|
||||||
closed chan bool
|
|
||||||
err error
|
err error
|
||||||
conn net.Conn
|
conn net.Conn
|
||||||
reader *bufio.Reader
|
cf codec.Codec
|
||||||
|
context context.Context
|
||||||
request client.Request
|
request client.Request
|
||||||
|
closed chan bool
|
||||||
|
reader *bufio.Reader
|
||||||
|
address string
|
||||||
|
ct string
|
||||||
|
opts client.CallOptions
|
||||||
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var errShutdown = fmt.Errorf("connection is shut down")
|
||||||
errShutdown = fmt.Errorf("connection is shut down")
|
|
||||||
)
|
|
||||||
|
|
||||||
func (h *httpStream) isClosed() bool {
|
func (h *httpStream) isClosed() bool {
|
||||||
select {
|
select {
|
||||||
@@ -65,13 +61,11 @@ func (h *httpStream) Send(msg interface{}) error {
|
|||||||
return errShutdown
|
return errShutdown
|
||||||
}
|
}
|
||||||
|
|
||||||
hreq, err := newRequest(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
|
||||||
}
|
}
|
||||||
|
|
||||||
hreq.Header = h.header
|
|
||||||
|
|
||||||
return hreq.Write(h.conn)
|
return hreq.Write(h.conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,34 +106,39 @@ func (h *httpStream) Close() error {
|
|||||||
func (h *httpStream) parseRsp(ctx context.Context, 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
|
||||||
|
|
||||||
// fast path return
|
select {
|
||||||
if hrsp.StatusCode == http.StatusNoContent {
|
case <-ctx.Done():
|
||||||
return nil
|
err = ctx.Err()
|
||||||
}
|
default:
|
||||||
|
// fast path return
|
||||||
if hrsp.StatusCode < 400 {
|
if hrsp.StatusCode == http.StatusNoContent {
|
||||||
if err = cf.ReadBody(hrsp.Body, rsp); err != nil {
|
return nil
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
if hrsp.StatusCode < 400 {
|
||||||
if ok && errmap != nil {
|
if err = cf.ReadBody(hrsp.Body, rsp); err != nil {
|
||||||
if err, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
err, ok = errmap["default"].(error)
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
buf, err := io.ReadAll(hrsp.Body)
|
|
||||||
if err != nil {
|
|
||||||
errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
|
||||||
}
|
|
||||||
|
|
||||||
if cerr := cf.ReadBody(hrsp.Body, err); cerr != nil {
|
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||||
err = errors.InternalServerError("go.micro.client", cerr.Error())
|
if ok && errmap != nil {
|
||||||
|
if err, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
||||||
|
err, ok = errmap["default"].(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
if cerr := cf.ReadBody(hrsp.Body, err); cerr != nil {
|
||||||
|
err = errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
|
215
util.go
215
util.go
@@ -10,32 +10,62 @@ 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
|
||||||
)
|
)
|
||||||
|
|
||||||
func newPathRequest(path string, method string, body string, msg interface{}, tags []string) (string, interface{}, error) {
|
// Error struct holds error
|
||||||
|
type Error struct {
|
||||||
|
err interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error func for error interface
|
||||||
|
func (err *Error) Error() string {
|
||||||
|
return fmt.Sprintf("%v", err.err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetError(err error) interface{} {
|
||||||
|
if rerr, ok := err.(*Error); ok {
|
||||||
|
return rerr.err
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPathRequest(path string, method string, body string, msg interface{}, tags []string, parameters map[string]map[string]string) (string, interface{}, error) {
|
||||||
// parse via https://github.com/googleapis/googleapis/blob/master/google/api/http.proto definition
|
// 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)
|
||||||
@@ -87,26 +117,38 @@ 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, nestif
|
||||||
if _, ok := fieldsmap[t.name]; ok {
|
if _, ok := fieldsmap[t.name]; ok {
|
||||||
if val.Type().Kind() == reflect.Slice {
|
switch val.Type().Kind() {
|
||||||
|
case reflect.Slice:
|
||||||
for idx := 0; idx < val.Len(); idx++ {
|
for idx := 0; idx < val.Len(); idx++ {
|
||||||
values.Add(t.name, fmt.Sprintf("%v", val.Index(idx).Interface()))
|
values.Add(t.name, fmt.Sprintf("%v", val.Index(idx).Interface()))
|
||||||
}
|
}
|
||||||
fieldsmapskip[t.name] = struct{}{}
|
fieldsmapskip[t.name] = struct{}{}
|
||||||
} else {
|
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 {
|
} else if (body == "*" || body == t.name) && method != http.MethodGet {
|
||||||
tnmsg.Field(i).Set(val)
|
if tnmsg.Field(i).CanSet() {
|
||||||
|
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++ {
|
||||||
@@ -127,13 +169,36 @@ 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
|
||||||
}
|
}
|
||||||
} else {
|
// nolint: nestif
|
||||||
|
if vs > 0 && ve != 0 {
|
||||||
|
if vm, ok := fieldsmap[fld[vs:ve]]; ok {
|
||||||
|
if vm != "" {
|
||||||
|
_, _ = b.WriteString(fld[vf : vs-1])
|
||||||
|
_, _ = b.WriteString(vm)
|
||||||
|
vf = ve + 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_, _ = b.WriteString(fld)
|
||||||
|
}
|
||||||
|
vs = 0
|
||||||
|
ve = 0
|
||||||
|
pholder = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !pholder {
|
||||||
_, _ = b.WriteString(fld)
|
_, _ = b.WriteString(fld)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,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
|
||||||
}
|
}
|
||||||
@@ -150,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 {
|
||||||
@@ -159,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()
|
||||||
@@ -173,45 +242,71 @@ func newTemplate(path string) (util.Template, 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 {
|
||||||
// fast path return
|
var err error
|
||||||
if hrsp.StatusCode == http.StatusNoContent {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := DefaultContentType
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
if htype := hrsp.Header.Get("Content-Type"); htype != "" {
|
err = ctx.Err()
|
||||||
ct = htype
|
default:
|
||||||
}
|
// fast path return
|
||||||
|
if hrsp.StatusCode == http.StatusNoContent {
|
||||||
cf, err := h.newCodec(ct)
|
return nil
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
if hrsp.StatusCode < 400 {
|
|
||||||
if err := cf.ReadBody(hrsp.Body, rsp); err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
}
|
||||||
return nil
|
ct := DefaultContentType
|
||||||
}
|
|
||||||
|
|
||||||
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
if htype := hrsp.Header.Get("Content-Type"); htype != "" {
|
||||||
if ok && errmap != nil {
|
ct = htype
|
||||||
if err, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)].(error); !ok {
|
}
|
||||||
err, ok = errmap["default"].(error)
|
|
||||||
|
cf, cerr := h.newCodec(ct)
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
|
||||||
|
// succeseful response
|
||||||
|
if hrsp.StatusCode < 400 {
|
||||||
|
if err = cf.ReadBody(hrsp.Body, rsp); err != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", err.Error())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// response with error
|
||||||
|
var rerr interface{}
|
||||||
|
errmap, ok := opts.Context.Value(errorMapKey{}).(map[string]interface{})
|
||||||
|
if ok && errmap != nil {
|
||||||
|
rerr, ok = errmap[fmt.Sprintf("%d", hrsp.StatusCode)]
|
||||||
|
if !ok {
|
||||||
|
rerr, ok = errmap["default"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok || rerr == nil {
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
if cerr := cf.ReadBody(hrsp.Body, rerr); cerr != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", cerr.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err, ok = rerr.(error); !ok {
|
||||||
|
err = &Error{rerr}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
buf, err := io.ReadAll(hrsp.Body)
|
|
||||||
if err != nil {
|
|
||||||
errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
return errors.New("go.micro.client", string(buf), int32(hrsp.StatusCode))
|
|
||||||
}
|
|
||||||
|
|
||||||
if cerr := cf.ReadBody(hrsp.Body, err); cerr != nil {
|
|
||||||
err = errors.InternalServerError("go.micro.client", cerr.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
|
38
util_test.go
38
util_test.go
@@ -5,28 +5,46 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestTemplate(t *testing.T) {
|
func TestParsing(t *testing.T) {
|
||||||
tpl, err := newTemplate("/v1/{ClientID}/list")
|
type Message struct {
|
||||||
if err != nil {
|
IIN string `protobuf:"bytes,1,opt,name=iin,proto3" json:"iin"`
|
||||||
t.Fatal(err)
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
u, err := url.Parse(path)
|
||||||
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ = tpl
|
|
||||||
// fmt.Printf("%#+v\n", tpl.Pool)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewPathRequest(t *testing.T) {
|
func TestNewPathRequest(t *testing.T) {
|
||||||
type Message struct {
|
type Message struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
||||||
Val2 int64
|
|
||||||
Val3 []string
|
Val3 []string
|
||||||
|
Val2 int64
|
||||||
}
|
}
|
||||||
|
|
||||||
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
@@ -45,8 +63,8 @@ func TestNewPathVarRequest(t *testing.T) {
|
|||||||
type Message struct {
|
type Message struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
Val1 string `protobuf:"bytes,1,opt,name=val1,proto3" json:"val1"`
|
||||||
Val2 int64
|
|
||||||
Val3 []string
|
Val3 []string
|
||||||
|
Val2 int64
|
||||||
}
|
}
|
||||||
|
|
||||||
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
omsg := &Message{Name: "test_name", Val1: "test_val1", Val2: 100, Val3: []string{"slice"}}
|
||||||
@@ -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