Compare commits

..

6 Commits

Author SHA1 Message Date
76a0bdd67c Merge pull request 'update for latest micro changes' (#114) from options into master
Reviewed-on: #114
2023-08-12 13:18:05 +03:00
8de525a8f8 update for latest micro changes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-08-12 13:17:47 +03:00
ef36082f2e Merge pull request 'fix request/response md handling' (#112) from request-respone-md into master
Reviewed-on: #112
2023-07-11 00:48:38 +03:00
21c897be47 fix request/response md handling
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-07-11 00:47:36 +03:00
0b21dd6660 Merge pull request 'move to micro v4' (#109) from v4 into master
Reviewed-on: #109
2023-04-28 22:29:44 +03:00
18eb0d9e5c move to micro v4
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-04-28 22:29:18 +03:00
26 changed files with 476 additions and 567 deletions

View File

@@ -1,29 +0,0 @@
name: lint
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup deps
run: go get -v ./...
- name: run lint
uses: https://github.com/golangci/golangci-lint-action@v6
with:
version: 'latest'

View File

@@ -1,34 +0,0 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
push:
branches:
- master
- v3
- v4
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup deps
run: go get -v ./...
- name: run test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...

View File

@@ -1,53 +0,0 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
push:
branches:
- master
- v3
- v4
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: checkout tests
uses: actions/checkout@v4
with:
ref: master
filter: 'blob:none'
repository: unistack-org/micro-tests
path: micro-tests
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup go work
env:
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: |
go work init
go work use .
go work use micro-tests
- name: setup deps
env:
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: go get -v ./...
- name: run tests
env:
INTEGRATION_TESTS: yes
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: |
cd micro-tests
go test -mod readonly -v ./... || true

19
.github/dependabot.yml vendored Normal file
View 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/workflows/autoapprove.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: "autoapprove"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
autoapprove:
runs-on: ubuntu-latest
steps:
- name: approve
uses: hmarr/auto-approve-action@v3
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
id: approve
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

21
.github/workflows/automerge.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: "automerge"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
automerge:
runs-on: ubuntu-latest
if: github.actor == 'vtolstov'
steps:
- name: merge
id: merge
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.TOKEN}}

47
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
name: build
on:
push:
branches:
- master
- v3
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
- name: checkout
uses: actions/checkout@v3
- name: cache
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v3
- name: lint
uses: golangci/golangci-lint-action@v3.4.0
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

78
.github/workflows/codeql-analysis.yml vendored Normal file
View 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@v3
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
# Initializes the CodeQL tools for scanning.
- name: init
uses: github/codeql-action/init@v2
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@v2
# 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@v2

View File

@@ -0,0 +1,27 @@
name: "dependabot-automerge"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
automerge:
runs-on: ubuntu-latest
if: github.actor == 'dependabot[bot]'
steps:
- name: metadata
id: metadata
uses: dependabot/fetch-metadata@v1.3.6
with:
github-token: "${{ secrets.TOKEN }}"
- name: merge
id: 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}}

47
.github/workflows/pr.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
name: prbuild
on:
pull_request:
branches:
- master
- v3
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
- name: checkout
uses: actions/checkout@v3
- name: cache
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v3
- name: lint
uses: golangci/golangci-lint-action@v3.4.0
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

39
.gitignore vendored
View File

@@ -1,39 +0,0 @@
# Develop tools
/.vscode/
/.idea/
.idea
.vscode
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Folders
_obj
_test
_build
.DS_Store
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# vim temp files
*~
*.swp
*.swo

View File

@@ -1,5 +1,44 @@
run: run:
concurrency: 8 concurrency: 4
deadline: 5m deadline: 5m
issues-exit-code: 1 issues-exit-code: 1
tests: true 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

View File

@@ -5,14 +5,14 @@ This plugin is a http client for micro.
## Overview ## Overview
The http client wraps `net/http` to provide a robust micro client with service discovery, load balancing and streaming. The http client wraps `net/http` to provide a robust micro client with service discovery, load balancing and streaming.
It complies with the [micro.Client](https://godoc.org/go.unistack.org/micro-client-http/v3#Client) interface. It complies with the [micro.Client](https://godoc.org/go.unistack.org/micro-client-http/v4#Client) interface.
## Usage ## Usage
### Use directly ### Use directly
```go ```go
import "go.unistack.org/micro-client-http/v3" import "go.unistack.org/micro-client-http/v4"
service := micro.NewService( service := micro.NewService(
micro.Name("my.service"), micro.Name("my.service"),

18
go.mod
View File

@@ -1,19 +1,5 @@
module go.unistack.org/micro-client-http/v4 module go.unistack.org/micro-client-http/v4
go 1.22.0 go 1.19
require go.unistack.org/micro/v4 v4.1.2 require go.unistack.org/micro/v4 v4.0.6
require (
github.com/ash3in/uuidv8 v1.2.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/matoous/go-nanoid v1.5.1 // indirect
github.com/spf13/cast v1.7.1 // indirect
go.unistack.org/micro-proto/v4 v4.1.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 // indirect
google.golang.org/grpc v1.69.4 // indirect
google.golang.org/protobuf v1.36.3 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

47
go.sum
View File

@@ -1,43 +1,4 @@
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= go.unistack.org/micro/v4 v4.0.1 h1:xo1IxbVfgh8i0eY0VeYa3cbb13u5n/Mxnp3FOgWD4Jo=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= go.unistack.org/micro/v4 v4.0.1/go.mod h1:p/J5UcSJjfHsWGT31uKoghQ5rUQZzQJBAFy+Z4+ZVMs=
github.com/ash3in/uuidv8 v1.2.0 h1:2oogGdtCPwaVtyvPPGin4TfZLtOGE5F+W++E880G6SI= go.unistack.org/micro/v4 v4.0.6 h1:YFWvTh3VwyOd6NHYTQcf47n2TF5+p/EhpnbuBQX3qhk=
github.com/ash3in/uuidv8 v1.2.0/go.mod h1:BnU0wJBxnzdEKmVg4xckBkD+VZuecTFTUP3M0dWgyY4= go.unistack.org/micro/v4 v4.0.6/go.mod h1:bVEYTlPi0EsdgZZt311bIroDg9ict7ky3C87dSCCAGk=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/matoous/go-nanoid v1.5.1 h1:aCjdvTyO9LLnTIi0fgdXhOPPvOHjpXN6Ik9DaNjIct4=
github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
go.unistack.org/micro-proto/v4 v4.1.0 h1:qPwL2n/oqh9RE3RTTDgt28XK3QzV597VugQPaw9lKUk=
go.unistack.org/micro-proto/v4 v4.1.0/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec=
go.unistack.org/micro/v4 v4.1.2 h1:9SOlPYyPNNFpg1A7BsvhDyQm3gysLH1AhWbDCp1hyoY=
go.unistack.org/micro/v4 v4.1.2/go.mod h1:lr3oYED8Ay1vjK68QqRw30QOtdk/ffpZqMFDasOUhKw=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 h1:Z7FRVJPSMaHQxD0uXU8WdgFh8PseLM8Q8NzhnpMrBhQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA=
google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A=
google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU=
google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

238
http.go
View File

@@ -1,16 +1,15 @@
// Package http provides a http client // Package http provides a http client
package http // import "go.unistack.org/micro-client-http/v3" package http // import "go.unistack.org/micro-client-http/v4"
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io" "io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -22,8 +21,6 @@ import (
"go.unistack.org/micro/v4/metadata" "go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/options" "go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/selector" "go.unistack.org/micro/v4/selector"
"go.unistack.org/micro/v4/semconv"
"go.unistack.org/micro/v4/tracer"
rutil "go.unistack.org/micro/v4/util/reflect" rutil "go.unistack.org/micro/v4/util/reflect"
) )
@@ -37,11 +34,10 @@ func filterLabel(r []router.Route) []router.Route {
*/ */
type httpClient struct { type httpClient struct {
funcCall client.FuncCall
funcStream client.FuncStream
httpcli *http.Client httpcli *http.Client
opts client.Options opts client.Options
sync.RWMutex sync.RWMutex
init bool
} }
func newRequest(ctx context.Context, log logger.Logger, addr string, req client.Request, ct string, cf codec.Codec, msg interface{}, opts client.CallOptions) (*http.Request, error) { func newRequest(ctx context.Context, log logger.Logger, addr string, req client.Request, ct string, cf codec.Codec, msg interface{}, opts client.CallOptions) (*http.Request, error) {
@@ -119,7 +115,7 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
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) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
var nmsg interface{} var nmsg interface{}
@@ -130,12 +126,12 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
} }
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", "%+v", err) 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", "%+v", err) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
var cookies []*http.Cookie var cookies []*http.Cookie
@@ -143,7 +139,7 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
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 {
header[k] = append(header[k], v...) header.Set(k, v)
} }
} }
} }
@@ -152,13 +148,13 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
} }
if opts.RequestMetadata != nil { if opts.RequestMetadata != nil {
for k, v := range opts.RequestMetadata { for k, v := range opts.RequestMetadata {
header[k] = append(header[k], v...) header.Set(k, v)
} }
} }
if md, ok := metadata.FromOutgoingContext(ctx); ok { if md, ok := metadata.FromOutgoingContext(ctx); ok {
for k, v := range md { for k, v := range md {
header[k] = append(header[k], v...) header.Set(k, v)
} }
} }
@@ -178,11 +174,11 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
for k, required := range vm { for k, required := range vm {
v, err = rutil.StructFieldByPath(msg, k) v, err = rutil.StructFieldByPath(msg, k)
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", "%+v", err) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
if rutil.IsZero(v) { if rutil.IsZero(v) {
if required == "true" { if required == "true" {
return nil, errors.BadRequest("go.micro.client", "required field %s not set", k) return nil, errors.BadRequest("go.micro.client", fmt.Sprintf("required field %s not set", k))
} }
continue continue
} }
@@ -198,12 +194,12 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
b, err := cf.Marshal(nmsg) b, err := cf.Marshal(nmsg)
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", "%+v", err) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
var hreq *http.Request var hreq *http.Request
if len(b) > 0 { if len(b) > 0 {
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), io.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)) header.Set("Content-Length", fmt.Sprintf("%d", hreq.ContentLength))
} else { } else {
@@ -211,7 +207,7 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
} }
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", "%+v", err) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
hreq.Header = header hreq.Header = header
@@ -220,68 +216,68 @@ func newRequest(ctx context.Context, log logger.Logger, addr string, req client.
} }
if log.V(logger.DebugLevel) { if log.V(logger.DebugLevel) {
log.Debug(ctx, fmt.Sprintf("request %s to %s with headers %v body %s", method, u.String(), hreq.Header, b)) log.Debugf(ctx, "request %s to %s with headers %v body %s", method, u.String(), hreq.Header, b)
} }
return hreq, nil return hreq, nil
} }
func (c *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 {
ct := req.ContentType() ct := req.ContentType()
if len(opts.ContentType) > 0 { if len(opts.ContentType) > 0 {
ct = opts.ContentType ct = opts.ContentType
} }
cf, err := c.newCodec(ct) cf, err := h.newCodec(ct)
if err != nil { if err != nil {
return errors.BadRequest("go.micro.client", "%+v", err) return errors.BadRequest("go.micro.client", err.Error())
} }
hreq, err := newRequest(ctx, c.opts.Logger, addr, req, ct, cf, req.Body(), opts) hreq, err := newRequest(ctx, h.opts.Logger, addr, req, ct, cf, req.Body(), opts)
if err != nil { if err != nil {
return err return err
} }
// make the request // make the request
hrsp, err := c.httpcli.Do(hreq) hrsp, err := h.httpcli.Do(hreq)
if err != nil { if err != nil {
switch err := err.(type) { switch err := err.(type) {
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", "%+v", err) return errors.Timeout("go.micro.client", err.Error())
} }
case net.Error: case net.Error:
if err.Timeout() { if err.Timeout() {
return errors.Timeout("go.micro.client", "%+v", err) return errors.Timeout("go.micro.client", err.Error())
} }
} }
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
defer hrsp.Body.Close() defer hrsp.Body.Close()
return c.parseRsp(ctx, hrsp, rsp, opts) return h.parseRsp(ctx, hrsp, rsp, opts)
} }
func (c *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) {
ct := req.ContentType() ct := req.ContentType()
if len(opts.ContentType) > 0 { if len(opts.ContentType) > 0 {
ct = opts.ContentType ct = opts.ContentType
} }
// get codec // get codec
cf, err := c.newCodec(ct) cf, err := h.newCodec(ct)
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", "%+v", err) return nil, errors.BadRequest("go.micro.client", err.Error())
} }
cc, err := (c.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", "Error dialing: %v", err) return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error dialing: %v", err))
} }
return &httpStream{ return &httpStream{
address: addr, address: addr,
logger: c.opts.Logger, logger: h.opts.Logger,
context: ctx, context: ctx,
closed: make(chan bool), closed: make(chan bool),
opts: opts, opts: opts,
@@ -293,78 +289,56 @@ func (c *httpClient) stream(ctx context.Context, addr string, req client.Request
}, nil }, nil
} }
func (c *httpClient) newCodec(ct string) (codec.Codec, error) { func (h *httpClient) newCodec(ct string) (codec.Codec, error) {
c.RLock() h.RLock()
defer h.RUnlock()
if idx := strings.IndexRune(ct, ';'); idx >= 0 { if idx := strings.IndexRune(ct, ';'); idx >= 0 {
ct = ct[:idx] ct = ct[:idx]
} }
if cf, ok := c.opts.Codecs[ct]; ok { if c, ok := h.opts.Codecs[ct]; ok {
c.RUnlock() return c, nil
return cf, nil
} }
c.RUnlock()
return nil, codec.ErrUnknownContentType return nil, codec.ErrUnknownContentType
} }
func (c *httpClient) Init(opts ...client.Option) error { func (h *httpClient) Init(opts ...options.Option) error {
if len(opts) == 0 && h.init {
return nil
}
for _, o := range opts { for _, o := range opts {
o(&c.opts) o(&h.opts)
} }
c.funcCall = c.fnCall if err := h.opts.Tracer.Init(); err != nil {
c.funcStream = c.fnStream return err
}
c.opts.Hooks.EachPrev(func(hook options.Hook) { if err := h.opts.Router.Init(); err != nil {
switch h := hook.(type) { return err
case client.HookCall: }
c.funcCall = h(c.funcCall) if err := h.opts.Logger.Init(); err != nil {
case client.HookStream: return err
c.funcStream = h(c.funcStream) }
if err := h.opts.Meter.Init(); err != nil {
return err
} }
})
return nil return nil
} }
func (c *httpClient) Options() client.Options { func (h *httpClient) Options() client.Options {
return c.opts return h.opts
} }
func (c *httpClient) NewRequest(service, method string, req interface{}, opts ...client.RequestOption) client.Request { func (h *httpClient) NewRequest(service, method string, req interface{}, opts ...options.Option) client.Request {
return newHTTPRequest(service, method, req, c.opts.ContentType, opts...) return newHTTPRequest(service, method, req, h.opts.ContentType, opts...)
} }
func (c *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error { func (h *httpClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...options.Option) error {
ts := time.Now()
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
var sp tracer.Span
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
tracer.WithSpanKind(tracer.SpanKindClient),
tracer.WithSpanLabels("endpoint", req.Endpoint()),
)
err := c.funcCall(ctx, req, rsp, opts...)
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
te := time.Since(ts)
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
if me := errors.FromError(err); me == nil {
sp.Finish()
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "success", "code", strconv.Itoa(int(200))).Inc()
} else {
sp.SetStatus(tracer.SpanStatusError, err.Error())
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "failure", "code", strconv.Itoa(int(me.Code))).Inc()
}
return err
}
func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
// make a copy of call opts // make a copy of call opts
callOpts := c.opts.CallOptions callOpts := h.opts.CallOptions
for _, opt := range opts { for _, opt := range opts {
opt(&callOpts) opt(&callOpts)
} }
@@ -379,8 +353,9 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
} 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(time.Until(d)) if err := options.Set(&callOpts, time.Until(d), ".RequestTimeout"); err != nil {
opt(&callOpts) return errors.New("go.micro.client", fmt.Sprintf("%v", err.Error()), 400)
}
} }
// should we noop right here? // should we noop right here?
@@ -391,21 +366,26 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
} }
// make copy of call method // make copy of call method
hcall := c.call hcall := h.call
// wrap the call in reverse
//for i := len(callOpts.CallWrappers); i > 0; i-- {
// hcall = callOpts.CallWrappers[i-1](hcall)
//}
// use the router passed as a call option, or fallback to the rpc clients router // use the router passed as a call option, or fallback to the rpc clients router
if callOpts.Router == nil { if callOpts.Router == nil {
callOpts.Router = c.opts.Router callOpts.Router = h.opts.Router
} }
if callOpts.Selector == nil { if callOpts.Selector == nil {
callOpts.Selector = c.opts.Selector callOpts.Selector = h.opts.Selector
} }
// inject proxy address // inject proxy address
// TODO: don't even bother using Lookup/Select in this case // TODO: don't even bother using Lookup/Select in this case
if len(c.opts.Proxy) > 0 { if len(h.opts.Proxy) > 0 {
callOpts.Address = []string{c.opts.Proxy} callOpts.Address = []string{h.opts.Proxy}
} }
var next selector.Next var next selector.Next
@@ -415,7 +395,7 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
// 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, err := callOpts.Backoff(ctx, req, i)
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
// only sleep if greater than 0 // only sleep if greater than 0
@@ -427,9 +407,9 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
var routes []string var routes []string
// lookup the route to send the reques to // lookup the route to send the reques to
// TODO apply any filtering here // TODO apply any filtering here
routes, err = c.opts.Lookup(ctx, req, callOpts) routes, err = h.opts.Lookup(ctx, req, callOpts)
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
// balance the list of nodes // balance the list of nodes
@@ -444,7 +424,7 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
// make the call // make the call
err = hcall(ctx, node, req, rsp, callOpts) err = hcall(ctx, node, req, rsp, 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 := c.opts.Selector.Record(node, err); verr != nil { if verr := h.opts.Selector.Record(node, err); verr != nil {
return verr return verr
} }
@@ -489,36 +469,11 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
return gerr return gerr
} }
func (c *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 ...options.Option) (client.Stream, error) {
ts := time.Now()
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
var sp tracer.Span
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
tracer.WithSpanKind(tracer.SpanKindClient),
tracer.WithSpanLabels("endpoint", req.Endpoint()),
)
stream, err := c.funcStream(ctx, req, opts...)
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
te := time.Since(ts)
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
if me := errors.FromError(err); me == nil {
sp.Finish()
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "success", "code", strconv.Itoa(int(200))).Inc()
} else {
sp.SetStatus(tracer.SpanStatusError, err.Error())
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "failure", "code", strconv.Itoa(int(me.Code))).Inc()
}
return stream, err
}
func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
var err error var err error
// make a copy of call opts // make a copy of call opts
callOpts := c.opts.CallOptions callOpts := h.opts.CallOptions
for _, o := range opts { for _, o := range opts {
o(&callOpts) o(&callOpts)
} }
@@ -533,8 +488,9 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
} 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
o := client.WithStreamTimeout(time.Until(d)) if err = options.Set(&callOpts, time.Until(d), ".StreamTimeout"); err != nil {
o(&callOpts) return nil, errors.New("go.micro.client", fmt.Sprintf("%v", err.Error()), 400)
}
} }
// should we noop right here? // should we noop right here?
@@ -555,17 +511,17 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
// use the router passed as a call option, or fallback to the rpc clients router // use the router passed as a call option, or fallback to the rpc clients router
if callOpts.Router == nil { if callOpts.Router == nil {
callOpts.Router = c.opts.Router callOpts.Router = h.opts.Router
} }
if callOpts.Selector == nil { if callOpts.Selector == nil {
callOpts.Selector = c.opts.Selector callOpts.Selector = h.opts.Selector
} }
// inject proxy address // inject proxy address
// TODO: don't even bother using Lookup/Select in this case // TODO: don't even bother using Lookup/Select in this case
if len(c.opts.Proxy) > 0 { if len(h.opts.Proxy) > 0 {
callOpts.Address = []string{c.opts.Proxy} callOpts.Address = []string{h.opts.Proxy}
} }
var next selector.Next var next selector.Next
@@ -574,7 +530,7 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
// call backoff first. Someone may want an initial start delay // call backoff first. Someone may want an initial start delay
t, cerr := callOpts.Backoff(ctx, req, i) t, cerr := callOpts.Backoff(ctx, req, i)
if cerr != nil { if cerr != nil {
return nil, errors.InternalServerError("go.micro.client", "%+v", cerr) return nil, errors.InternalServerError("go.micro.client", cerr.Error())
} }
// only sleep if greater than 0 // only sleep if greater than 0
@@ -586,9 +542,9 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
var routes []string var routes []string
// lookup the route to send the reques to // lookup the route to send the reques to
// TODO apply any filtering here // TODO apply any filtering here
routes, err = c.opts.Lookup(ctx, req, callOpts) routes, err = h.opts.Lookup(ctx, req, callOpts)
if err != nil { if err != nil {
return nil, errors.InternalServerError("go.micro.client", "%+v", err) return nil, errors.InternalServerError("go.micro.client", err.Error())
} }
// balance the list of nodes // balance the list of nodes
@@ -600,10 +556,10 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
node := next() node := next()
stream, cerr := c.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 := c.opts.Selector.Record(node, cerr); verr != nil { if verr := h.opts.Selector.Record(node, cerr); verr != nil {
return nil, verr return nil, verr
} }
@@ -654,22 +610,22 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
return nil, grr return nil, grr
} }
func (c *httpClient) String() string { func (h *httpClient) String() string {
return "http" return "http"
} }
func (c *httpClient) Name() string { func (h *httpClient) Name() string {
return c.opts.Name return h.opts.Name
} }
func NewClient(opts ...client.Option) *httpClient { func NewClient(opts ...options.Option) client.Client {
options := client.NewOptions(opts...) options := client.NewOptions(opts...)
if len(options.ContentType) == 0 { if len(options.ContentType) == 0 {
options.ContentType = DefaultContentType options.ContentType = DefaultContentType
} }
c := &httpClient{ rc := &httpClient{
opts: options, opts: options,
} }
@@ -692,7 +648,7 @@ func NewClient(opts ...client.Option) *httpClient {
} }
if httpcli, ok := options.Context.Value(httpClientKey{}).(*http.Client); ok { if httpcli, ok := options.Context.Value(httpClientKey{}).(*http.Client); ok {
c.httpcli = httpcli rc.httpcli = httpcli
} else { } else {
// TODO customTransport := http.DefaultTransport.(*http.Transport).Clone() // TODO customTransport := http.DefaultTransport.(*http.Transport).Clone()
tr := &http.Transport{ tr := &http.Transport{
@@ -708,11 +664,9 @@ func NewClient(opts ...client.Option) *httpClient {
ExpectContinueTimeout: 1 * time.Second, ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: options.TLSConfig, TLSClientConfig: options.TLSConfig,
} }
c.httpcli = &http.Client{Transport: tr} rc.httpcli = &http.Client{Transport: tr}
} }
c := client.Client(rc)
c.funcCall = c.fnCall
c.funcStream = c.fnStream
return c return c
} }

View File

@@ -1,60 +1,21 @@
package http package http
import ( import (
"encoding/json"
"fmt"
"net/url" "net/url"
"strings" "strings"
"testing" "testing"
) )
func TestNestedPathPost(t *testing.T) { type Request struct {
req := &request{Name: "first", Field1: "fieldval"} Name string `json:"name"`
p, m, err := newPathRequest("/api/v1/xxxx", "POST", "*", req, []string{"json", "protobuf"}, nil) Field1 string `json:"field1"`
if err != nil { ClientID string
t.Fatal(err) Field2 string
} Field3 int64
u, err := url.Parse(p)
if err != nil {
t.Fatal(err)
}
if s := u.String(); s != "/api/v1/xxxx" {
t.Fatalf("nested path error %s", s)
}
_ = m
}
type request struct {
NestedTest *request `json:"nested_test,omitempty"`
Name string `json:"name,omitempty"`
Field1 string `json:"field1,omitempty"`
ClientID string `json:",omitempty"`
Field2 string `json:",omitempty"`
Field3 int64 `json:",omitempty"`
}
func TestNestedPath(t *testing.T) {
req := &request{Name: "first", NestedTest: &request{Name: "second"}, Field1: "fieldval"}
p, m, err := newPathRequest("/api/v1/{name}/{nested_test.name}", "PUT", "*", req, []string{"json", "protobuf"}, nil)
if err != nil {
t.Fatal(err)
}
u, err := url.Parse(p)
if err != nil {
t.Fatal(err)
}
if s := u.String(); s != "/api/v1/first/second" {
t.Fatalf("nested path error %s", s)
}
b, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
fmt.Printf("m %#+v %s\n", m, b)
} }
func TestPathWithHeader(t *testing.T) { func TestPathWithHeader(t *testing.T) {
req := &request{Name: "vtolstov", Field1: "field1", ClientID: "1234567890"} req := &Request{Name: "vtolstov", Field1: "field1", ClientID: "1234567890"}
p, m, err := newPathRequest( p, m, err := newPathRequest(
"/api/v1/test?Name={name}&Field1={field1}", "/api/v1/test?Name={name}&Field1={field1}",
"POST", "POST",
@@ -79,7 +40,7 @@ func TestPathWithHeader(t *testing.T) {
} }
func TestPathValues(t *testing.T) { func TestPathValues(t *testing.T) {
req := &request{Name: "vtolstov", Field1: "field1"} req := &Request{Name: "vtolstov", Field1: "field1"}
p, m, err := newPathRequest("/api/v1/test?Name={name}&Field1={field1}", "POST", "*", req, nil, nil) p, m, err := newPathRequest("/api/v1/test?Name={name}&Field1={field1}", "POST", "*", req, nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -95,7 +56,7 @@ func TestPathValues(t *testing.T) {
} }
func TestValidPath(t *testing.T) { func TestValidPath(t *testing.T) {
req := &request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10} req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil, nil) p, m, err := newPathRequest("/api/v1/{name}/list", "GET", "", req, nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -112,9 +73,9 @@ func TestValidPath(t *testing.T) {
} }
func TestInvalidPath(t *testing.T) { func TestInvalidPath(t *testing.T) {
req := &request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10} req := &Request{Name: "vtolstov", Field1: "field1", Field2: "field2", Field3: 10}
s, _, err := newPathRequest("/api/v1/{xname}/list", "GET", "", req, nil, 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: %s", s) t.Fatal("path param must not be filled")
} }
} }

View File

@@ -4,8 +4,8 @@ import (
"net" "net"
"net/http" "net/http"
"go.unistack.org/micro/v4/client"
"go.unistack.org/micro/v4/metadata" "go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/options"
) )
var ( var (
@@ -29,98 +29,98 @@ var (
type poolMaxStreams struct{} type poolMaxStreams struct{}
// PoolMaxStreams maximum streams on a connectioin // PoolMaxStreams maximum streams on a connectioin
func PoolMaxStreams(n int) client.Option { func PoolMaxStreams(n int) options.Option {
return client.SetOption(poolMaxStreams{}, n) return options.ContextOption(poolMaxStreams{}, n)
} }
type poolMaxIdle struct{} type poolMaxIdle struct{}
// PoolMaxIdle maximum idle conns of a pool // PoolMaxIdle maximum idle conns of a pool
func PoolMaxIdle(d int) client.Option { func PoolMaxIdle(d int) options.Option {
return client.SetOption(poolMaxIdle{}, d) return options.ContextOption(poolMaxIdle{}, d)
} }
type maxRecvMsgSizeKey struct{} type maxRecvMsgSizeKey struct{}
// MaxRecvMsgSize set the maximum size of message that client can receive. // MaxRecvMsgSize set the maximum size of message that client can receive.
func MaxRecvMsgSize(s int) client.Option { func MaxRecvMsgSize(s int) options.Option {
return client.SetOption(maxRecvMsgSizeKey{}, s) return options.ContextOption(maxRecvMsgSizeKey{}, s)
} }
type maxSendMsgSizeKey struct{} type maxSendMsgSizeKey struct{}
// MaxSendMsgSize set the maximum size of message that client can send. // MaxSendMsgSize set the maximum size of message that client can send.
func MaxSendMsgSize(s int) client.Option { func MaxSendMsgSize(s int) options.Option {
return client.SetOption(maxSendMsgSizeKey{}, s) return options.ContextOption(maxSendMsgSizeKey{}, s)
} }
type httpClientKey struct{} type httpClientKey struct{}
// nolint: golint // nolint: golint
// HTTPClient pass http.Client option to client Call // HTTPClient pass http.Client option to client Call
func HTTPClient(c *http.Client) client.Option { func HTTPClient(c *http.Client) options.Option {
return client.SetOption(httpClientKey{}, c) return options.ContextOption(httpClientKey{}, c)
} }
type httpDialerKey struct{} type httpDialerKey struct{}
// nolint: golint // nolint: golint
// HTTPDialer pass net.Dialer option to client // HTTPDialer pass net.Dialer option to client
func HTTPDialer(d *net.Dialer) client.Option { func HTTPDialer(d *net.Dialer) options.Option {
return client.SetOption(httpDialerKey{}, d) return options.ContextOption(httpDialerKey{}, d)
} }
type methodKey struct{} type methodKey struct{}
// Method pass method option to client Call // Method pass method option to client Call
func Method(m string) client.CallOption { func Method(m string) options.Option {
return client.SetCallOption(methodKey{}, m) return options.ContextOption(methodKey{}, m)
} }
type pathKey struct{} type pathKey struct{}
// Path spcecifies path option to client Call // Path spcecifies path option to client Call
func Path(p string) client.CallOption { func Path(p string) options.Option {
return client.SetCallOption(pathKey{}, p) return options.ContextOption(pathKey{}, p)
} }
type bodyKey struct{} type bodyKey struct{}
// Body specifies body option to client Call // Body specifies body option to client Call
func Body(b string) client.CallOption { func Body(b string) options.Option {
return client.SetCallOption(bodyKey{}, b) return options.ContextOption(bodyKey{}, b)
} }
type errorMapKey struct{} type errorMapKey struct{}
func ErrorMap(m map[string]interface{}) client.CallOption { func ErrorMap(m map[string]interface{}) options.Option {
return client.SetCallOption(errorMapKey{}, m) return options.ContextOption(errorMapKey{}, m)
} }
type structTagsKey struct{} type structTagsKey struct{}
// StructTags pass tags slice option to client Call // StructTags pass tags slice option to client Call
func StructTags(tags []string) client.CallOption { func StructTags(tags []string) options.Option {
return client.SetCallOption(structTagsKey{}, tags) return options.ContextOption(structTagsKey{}, tags)
} }
type metadataKey struct{} type metadataKey struct{}
// Metadata pass metadata to client Call // Metadata pass metadata to client Call
func Metadata(md metadata.Metadata) client.CallOption { func Metadata(md metadata.Metadata) options.Option {
return client.SetCallOption(metadataKey{}, md) return options.ContextOption(metadataKey{}, md)
} }
type cookieKey struct{} type cookieKey struct{}
// Cookie pass cookie to client Call // Cookie pass cookie to client Call
func Cookie(cookies ...string) client.CallOption { func Cookie(cookies ...string) options.Option {
return client.SetCallOption(cookieKey{}, cookies) return options.ContextOption(cookieKey{}, cookies)
} }
type headerKey struct{} type headerKey struct{}
// Header pass cookie to client Call // Header pass cookie to client Call
func Header(headers ...string) client.CallOption { func Header(headers ...string) options.Option {
return client.SetCallOption(headerKey{}, headers) return options.ContextOption(headerKey{}, headers)
} }

View File

@@ -3,6 +3,7 @@ package http
import ( import (
"go.unistack.org/micro/v4/client" "go.unistack.org/micro/v4/client"
"go.unistack.org/micro/v4/codec" "go.unistack.org/micro/v4/codec"
"go.unistack.org/micro/v4/options"
) )
type httpRequest struct { type httpRequest struct {
@@ -13,7 +14,7 @@ type httpRequest struct {
opts client.RequestOptions opts client.RequestOptions
} }
func newHTTPRequest(service, method string, request interface{}, contentType string, opts ...client.RequestOption) client.Request { func newHTTPRequest(service, method string, request interface{}, contentType string, opts ...options.Option) client.Request {
options := client.NewRequestOptions(opts...) options := client.NewRequestOptions(opts...)
if len(options.ContentType) == 0 { if len(options.ContentType) == 0 {
options.ContentType = contentType options.ContentType = contentType

View File

@@ -90,7 +90,7 @@ func (h *httpStream) Recv(msg interface{}) error {
hrsp, err := http.ReadResponse(h.reader, new(http.Request)) hrsp, err := http.ReadResponse(h.reader, new(http.Request))
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
defer hrsp.Body.Close() defer hrsp.Body.Close()
@@ -134,19 +134,19 @@ func (h *httpStream) parseRsp(ctx context.Context, log logger.Logger, hrsp *http
buf, err = io.ReadAll(hrsp.Body) buf, err = io.ReadAll(hrsp.Body)
if err != nil { if err != nil {
if log.V(logger.ErrorLevel) { if log.V(logger.ErrorLevel) {
log.Error(ctx, "failed to read body", err) log.Errorf(ctx, "failed to read body: %v", err)
} }
return errors.InternalServerError("go.micro.client", "%s", buf) return errors.InternalServerError("go.micro.client", string(buf))
} }
} }
if log.V(logger.DebugLevel) { if log.V(logger.DebugLevel) {
log.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header)) log.Debugf(ctx, "response %s with %v", buf, hrsp.Header)
} }
if hrsp.StatusCode < 400 { if hrsp.StatusCode < 400 {
if err = cf.Unmarshal(buf, rsp); err != nil { if err = cf.Unmarshal(buf, rsp); err != nil {
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
return nil return nil
} }
@@ -163,7 +163,7 @@ func (h *httpStream) parseRsp(ctx context.Context, log logger.Logger, hrsp *http
} }
if cerr := cf.Unmarshal(buf, rerr); cerr != nil { if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
return errors.InternalServerError("go.micro.client", "%+v", cerr) return errors.InternalServerError("go.micro.client", cerr.Error())
} }
if err, ok = rerr.(error); !ok { if err, ok = rerr.(error); !ok {

80
util.go
View File

@@ -87,8 +87,6 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
values := url.Values{} values := url.Values{}
// copy cycle // copy cycle
cleanPath := make(map[string]bool)
for i := 0; i < tmsg.NumField(); i++ { for i := 0; i < tmsg.NumField(); i++ {
val := tmsg.Field(i) val := tmsg.Field(i)
if val.IsZero() { if val.IsZero() {
@@ -123,7 +121,6 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
default: default:
t = &tag{key: tn, name: tp[0]} t = &tag{key: tn, name: tp[0]}
} }
if t.name != "" { if t.name != "" {
break break
} }
@@ -157,64 +154,19 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
default: default:
fieldsmap[t.name] = getParam(val) fieldsmap[t.name] = getParam(val)
} }
} else { } else if (body == "*" || body == t.name) && method != http.MethodGet {
for k, v := range fieldsmap {
isSet := false
if v != "" {
continue
}
var clean []string
fld := msg
parts := strings.Split(k, ".")
for idx := 0; idx < len(parts); idx++ {
var nfld interface{}
var name string
if tags == nil {
tags = []string{"json"}
}
tagsloop:
for ti := 0; ti < len(tags); ti++ {
name, nfld, err = rutil.StructFieldNameByTag(fld, tags[ti], parts[idx])
if err == nil {
clean = append(clean, name)
break tagsloop
}
}
if err == nil {
fld = nfld
if len(parts)-1 == idx {
isSet = true
fieldsmap[k] = fmt.Sprintf("%v", fld)
}
}
}
if isSet {
cleanPath[strings.Join(clean, ".")] = true
}
}
for k := range cleanPath {
if err = rutil.ZeroFieldByPath(nmsg, k); err != nil {
return "", nil, err
}
}
if (body == "*" || body == t.name) && method != http.MethodGet {
if tnmsg.Field(i).CanSet() { if tnmsg.Field(i).CanSet() {
tnmsg.Field(i).Set(val) tnmsg.Field(i).Set(val)
} }
} else if method == http.MethodGet { } else {
if val.Type().Kind() == reflect.Slice { if val.Type().Kind() == reflect.Slice {
for idx := 0; idx < val.Len(); idx++ { for idx := 0; idx < val.Len(); idx++ {
values.Add(t.name, getParam(val.Index(idx))) values.Add(t.name, getParam(val.Index(idx)))
} }
} else if !rutil.IsEmpty(val) { } else {
values.Add(t.name, getParam(val)) values.Add(t.name, getParam(val))
} }
} }
}
} }
// check not filled stuff // check not filled stuff
@@ -265,23 +217,13 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
_, _ = b.WriteString(values.Encode()) _, _ = b.WriteString(values.Encode())
} }
// rutil.ZeroEmpty(tnmsg.Interface()) if rutil.IsZero(nmsg) {
if rutil.IsZero(nmsg) && !isEmptyStruct(nmsg) {
return b.String(), nil, nil return b.String(), nil, nil
} }
return b.String(), nmsg, nil return b.String(), nmsg, nil
} }
func isEmptyStruct(v interface{}) bool {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
return val.Kind() == reflect.Struct && val.NumField() == 0
}
func newTemplate(path string) ([]string, error) { func newTemplate(path string) ([]string, error) {
if len(path) == 0 || path[0] != '/' { if len(path) == 0 || path[0] != '/' {
return nil, fmt.Errorf("path must starts with /") return nil, fmt.Errorf("path must starts with /")
@@ -332,28 +274,28 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
buf, err = io.ReadAll(hrsp.Body) buf, err = io.ReadAll(hrsp.Body)
if err != nil { if err != nil {
if h.opts.Logger.V(logger.ErrorLevel) { if h.opts.Logger.V(logger.ErrorLevel) {
h.opts.Logger.Error(ctx, "failed to read body", err) h.opts.Logger.Errorf(ctx, "failed to read body: %v", err)
} }
return errors.InternalServerError("go.micro.client", "%s", buf) return errors.InternalServerError("go.micro.client", string(buf))
} }
} }
cf, cerr := h.newCodec(ct) cf, cerr := h.newCodec(ct)
if cerr != nil { if cerr != nil {
if h.opts.Logger.V(logger.DebugLevel) { if h.opts.Logger.V(logger.DebugLevel) {
h.opts.Logger.Debug(ctx, fmt.Sprintf("response with %v unknown content-type %s %s", hrsp.Header, ct, buf)) h.opts.Logger.Debugf(ctx, "response with %v unknown content-type %s %s", hrsp.Header, ct, buf)
} }
return errors.InternalServerError("go.micro.client", "%+v", cerr) return errors.InternalServerError("go.micro.client", cerr.Error())
} }
if h.opts.Logger.V(logger.DebugLevel) { if h.opts.Logger.V(logger.DebugLevel) {
h.opts.Logger.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header)) h.opts.Logger.Debugf(ctx, "response %s with %v", buf, hrsp.Header)
} }
// succeseful response // succeseful response
if hrsp.StatusCode < 400 { if hrsp.StatusCode < 400 {
if err = cf.Unmarshal(buf, rsp); err != nil { if err = cf.Unmarshal(buf, rsp); err != nil {
return errors.InternalServerError("go.micro.client", "%+v", err) return errors.InternalServerError("go.micro.client", err.Error())
} }
return nil return nil
} }
@@ -373,7 +315,7 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
} }
if cerr := cf.Unmarshal(buf, rerr); cerr != nil { if cerr := cf.Unmarshal(buf, rerr); cerr != nil {
return errors.InternalServerError("go.micro.client", "%+v", cerr) return errors.InternalServerError("go.micro.client", cerr.Error())
} }
if err, ok = rerr.(error); !ok { if err, ok = rerr.(error); !ok {

View File

@@ -1,7 +1,6 @@
package http package http
import ( import (
"net/http"
"net/url" "net/url"
"testing" "testing"
) )
@@ -53,49 +52,11 @@ func TestNewPathRequest(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
switch m {
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
break
case http.MethodGet:
vals := u.Query() vals := u.Query()
if v, ok := vals["name"]; !ok || v[0] != "test_name" { if v, ok := vals["name"]; !ok || v[0] != "test_name" {
t.Fatalf("%s invalid path: %v nmsg: %v", m, path, nmsg)
}
}
}
}
func TestNewPathRequestWithEmptyBody(t *testing.T) {
val := struct{}{}
cases := []string{
"",
"*",
"{}",
"nil",
`{"type": "invalid"}`,
}
for _, body := range cases {
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
path, nmsg, err := newPathRequest("/v1/test", m, body, val, []string{"protobuf", "json"}, nil)
if err != nil {
t.Fatal(err)
}
if nmsg == nil {
t.Fatalf("invalid path: nil nmsg")
}
u, err := url.Parse(path)
if err != nil {
t.Fatal(err)
}
vals := u.Query()
if len(vals) != 0 {
t.Fatalf("invalid path: %v nmsg: %v", path, nmsg) t.Fatalf("invalid path: %v nmsg: %v", path, nmsg)
} }
} }
}
} }
func TestNewPathVarRequest(t *testing.T) { func TestNewPathVarRequest(t *testing.T) {
@@ -126,7 +87,7 @@ func TestNewPathVarRequest(t *testing.T) {
t.Fatalf("invalid nmsg: %#+v\n", nmsg) t.Fatalf("invalid nmsg: %#+v\n", nmsg)
} }
if nmsg.(*Message).Name != "test_name" { if nmsg.(*Message).Name != "test_name" {
t.Fatalf("invalid path: %v nmsg: %#+v", path, nmsg) t.Fatalf("invalid nmsg: %v nmsg: %v", path, nmsg)
} }
} else { } else {
vals := u.Query() vals := u.Query()