Compare commits

..

7 Commits
v3.9.11 ... v3

Author SHA1 Message Date
a9829b5da0 Merge pull request 'move set content-type in client publish' (#123) from devstigneev/micro-client-http:v3 into v3
All checks were successful
test / test (push) Successful in 3m56s
Reviewed-on: #123
2025-01-18 15:38:23 +03:00
a770c498e7 move set content-type in client publish
All checks were successful
lint / lint (pull_request) Successful in 1m25s
test / test (pull_request) Successful in 2m56s
2025-01-17 17:57:44 +03:00
fa5602486a lintering && fix call hook (#122)
All checks were successful
test / test (push) Successful in 4m10s
Reviewed-on: #122
Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru>
Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
2024-12-18 20:43:01 +03:00
d5690ef2b7 Update workflows (#121)
All checks were successful
test / test (push) Successful in 2m31s
Co-authored-by: Aleksandr Tolstikhin <atolstikhin@mtsbank.ru>
Reviewed-on: #121
Co-authored-by: Александр Толстихин <tolstihin1996@mail.ru>
Co-committed-by: Александр Толстихин <tolstihin1996@mail.ru>
2024-12-11 00:35:07 +03:00
134031e18b update for latest micro logger changes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-12 13:26:11 +03:00
9743a7f9b1 update deps
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-09-20 18:45:01 +03:00
2225b95e3e try to fixup
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-20 08:55:24 +03:00
23 changed files with 279 additions and 362 deletions

View File

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

View File

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

View File

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

View File

@ -1,19 +0,0 @@
# 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"

View File

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

View File

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

View File

@ -1,47 +0,0 @@
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

View File

@ -1,78 +0,0 @@
# 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

@ -1,27 +0,0 @@
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}}

View File

@ -1,47 +0,0 @@
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 Normal file
View File

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

View File

@ -1,44 +1,5 @@
run: run:
concurrency: 4 concurrency: 8
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

15
go.mod
View File

@ -1,12 +1,15 @@
module go.unistack.org/micro-client-http/v3 module go.unistack.org/micro-client-http/v3
go 1.20 go 1.22
require go.unistack.org/micro/v3 v3.10.69 toolchain go1.23.1
require go.unistack.org/micro/v3 v3.10.97
require ( require (
golang.org/x/sys v0.19.0 // indirect go.unistack.org/micro-proto/v3 v3.4.1 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be // indirect golang.org/x/sys v0.26.0 // indirect
google.golang.org/grpc v1.63.2 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 // indirect
google.golang.org/protobuf v1.33.0 // indirect google.golang.org/grpc v1.67.1 // indirect
google.golang.org/protobuf v1.35.1 // indirect
) )

26
go.sum
View File

@ -1,13 +1,39 @@
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
go.unistack.org/micro/v3 v3.10.69 h1:V4g9LqUhzGab73U2aevnjtffCdJqGTuMfWY7fy4qGwI= go.unistack.org/micro/v3 v3.10.69 h1:V4g9LqUhzGab73U2aevnjtffCdJqGTuMfWY7fy4qGwI=
go.unistack.org/micro/v3 v3.10.69/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg= go.unistack.org/micro/v3 v3.10.69/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
go.unistack.org/micro/v3 v3.10.88 h1:MxlzP+77Y6Kphb3lzHxROL4XfE/WdCQMQpnPv4D9Z8U=
go.unistack.org/micro/v3 v3.10.88/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
go.unistack.org/micro/v3 v3.10.91 h1:vuJY4tXwpqimwIkEJ3TozMYNVQQs+C5QMlQWPgSY/YM=
go.unistack.org/micro/v3 v3.10.91/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
go.unistack.org/micro/v3 v3.10.97 h1:8l7fv+i06/PjPrBBhRC/ZQkWGIOuHPg3jJN0vktYE78=
go.unistack.org/micro/v3 v3.10.97/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be h1:LG9vZxsWGOmUKieR8wPAUR3u3MpnYFQZROPIMaXh7/A= google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be h1:LG9vZxsWGOmUKieR8wPAUR3u3MpnYFQZROPIMaXh7/A=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 h1:QCqS/PdaHTSWGvupk2F/ehwHtGc0/GYkT+3GAcR1CCc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI=
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM= google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA= google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/grpc v1.66.2 h1:3QdXkuq3Bkh7w+ywLdLvM56cmGvQHUMZpiCzt6Rqaoo=
google.golang.org/grpc v1.66.2/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y=
google.golang.org/grpc v1.67.0 h1:IdH9y6PF5MPSdAntIcpjQ+tXO41pcQsfZV2RxtQgVcw=
google.golang.org/grpc v1.67.0/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E=
google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=

49
http.go
View File

@ -6,7 +6,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -46,7 +46,6 @@ type httpClient struct {
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) {
@ -124,7 +123,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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
var nmsg interface{} var nmsg interface{}
@ -135,12 +134,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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
var cookies []*http.Cookie var cookies []*http.Cookie
@ -183,11 +182,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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
if rutil.IsZero(v) { if rutil.IsZero(v) {
if required == "true" { if required == "true" {
return nil, errors.BadRequest("go.micro.client", fmt.Sprintf("required field %s not set", k)) return nil, errors.BadRequest("go.micro.client", "required field %s not set", k)
} }
continue continue
} }
@ -203,12 +202,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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
var hreq *http.Request var hreq *http.Request
if len(b) > 0 { if len(b) > 0 {
hreq, err = http.NewRequestWithContext(ctx, method, u.String(), ioutil.NopCloser(bytes.NewBuffer(b))) hreq, err = http.NewRequestWithContext(ctx, method, u.String(), io.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 {
@ -216,7 +215,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", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
hreq.Header = header hreq.Header = header
@ -239,7 +238,7 @@ func (c *httpClient) call(ctx context.Context, addr string, req client.Request,
cf, err := c.newCodec(ct) cf, err := c.newCodec(ct)
if err != nil { if err != nil {
return errors.BadRequest("go.micro.client", err.Error()) return errors.BadRequest("go.micro.client", "%+v", err)
} }
hreq, err := newRequest(ctx, c.opts.Logger, addr, req, ct, cf, req.Body(), opts) hreq, err := newRequest(ctx, c.opts.Logger, addr, req, ct, cf, req.Body(), opts)
if err != nil { if err != nil {
@ -252,14 +251,14 @@ func (c *httpClient) call(ctx context.Context, addr string, req client.Request,
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", err.Error()) return errors.Timeout("go.micro.client", "%+v", err)
} }
case net.Error: case net.Error:
if err.Timeout() { if err.Timeout() {
return errors.Timeout("go.micro.client", err.Error()) return errors.Timeout("go.micro.client", "%+v", err)
} }
} }
return errors.InternalServerError("go.micro.client", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
defer hrsp.Body.Close() defer hrsp.Body.Close()
@ -276,12 +275,12 @@ func (c *httpClient) stream(ctx context.Context, addr string, req client.Request
// get codec // get codec
cf, err := c.newCodec(ct) cf, err := c.newCodec(ct)
if err != nil { if err != nil {
return nil, errors.BadRequest("go.micro.client", err.Error()) return nil, errors.BadRequest("go.micro.client", "%+v", err)
} }
cc, err := (c.httpcli.Transport).(*http.Transport).DialContext(ctx, "tcp", addr) cc, err := (c.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", "Error dialing: %v", err)
} }
return &httpStream{ return &httpStream{
@ -324,7 +323,7 @@ func (c *httpClient) Init(opts ...client.Option) error {
c.funcPublish = c.fnPublish c.funcPublish = c.fnPublish
c.funcBatchPublish = c.fnBatchPublish c.funcBatchPublish = c.fnBatchPublish
c.opts.Hooks.EachNext(func(hook options.Hook) { c.opts.Hooks.EachPrev(func(hook options.Hook) {
switch h := hook.(type) { switch h := hook.(type) {
case client.HookCall: case client.HookCall:
c.funcCall = h(c.funcCall) c.funcCall = h(c.funcCall)
@ -430,7 +429,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", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
// only sleep if greater than 0 // only sleep if greater than 0
@ -444,7 +443,7 @@ func (c *httpClient) fnCall(ctx context.Context, req client.Request, rsp interfa
// TODO apply any filtering here // TODO apply any filtering here
routes, err = c.opts.Lookup(ctx, req, callOpts) routes, err = c.opts.Lookup(ctx, req, callOpts)
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
// balance the list of nodes // balance the list of nodes
@ -589,7 +588,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", cerr.Error()) return nil, errors.InternalServerError("go.micro.client", "%+v", cerr)
} }
// only sleep if greater than 0 // only sleep if greater than 0
@ -603,7 +602,7 @@ func (c *httpClient) fnStream(ctx context.Context, req client.Request, opts ...c
// TODO apply any filtering here // TODO apply any filtering here
routes, err = c.opts.Lookup(ctx, req, callOpts) routes, err = c.opts.Lookup(ctx, req, callOpts)
if err != nil { if err != nil {
return nil, errors.InternalServerError("go.micro.client", err.Error()) return nil, errors.InternalServerError("go.micro.client", "%+v", err)
} }
// balance the list of nodes // balance the list of nodes
@ -709,7 +708,7 @@ func (c *httpClient) publish(ctx context.Context, ps []client.Message, opts ...c
for _, p := range ps { for _, p := range ps {
md := metadata.Copy(omd) md := metadata.Copy(omd)
md[metadata.HeaderContentType] = p.ContentType()
topic := p.Topic() topic := p.Topic()
if len(exchange) > 0 { if len(exchange) > 0 {
topic = exchange topic = exchange
@ -721,6 +720,8 @@ func (c *httpClient) publish(ctx context.Context, ps []client.Message, opts ...c
md.Set(k, v) md.Set(k, v)
} }
md[metadata.HeaderContentType] = p.ContentType()
// passed in raw data // passed in raw data
if d, ok := p.Payload().(*codec.Frame); ok { if d, ok := p.Payload().(*codec.Frame); ok {
body = d.Data body = d.Data
@ -728,12 +729,12 @@ func (c *httpClient) publish(ctx context.Context, ps []client.Message, opts ...c
// use codec for payload // use codec for payload
cf, err := c.newCodec(p.ContentType()) cf, err := c.newCodec(p.ContentType())
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
// set the body // set the body
b, err := cf.Marshal(p.Payload()) b, err := cf.Marshal(p.Payload())
if err != nil { if err != nil {
return errors.InternalServerError("go.micro.client", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
body = b body = b
} }

View File

@ -1,18 +1,36 @@
package http package http
import ( import (
"encoding/json"
"fmt"
"net/url" "net/url"
"strings" "strings"
"testing" "testing"
) )
func TestNestedPathPost(t *testing.T) {
req := &request{Name: "first", Field1: "fieldval"}
p, m, err := newPathRequest("/api/v1/xxxx", "POST", "*", req, []string{"json", "protobuf"}, nil)
if err != nil {
t.Fatal(err)
}
u, err := url.Parse(p)
if err != nil {
t.Fatal(err)
}
if s := u.String(); s != "/api/v1/xxxx" {
t.Fatalf("nested path error %s", s)
}
_ = m
}
type request struct { type request struct {
NestedTest *request `json:"nested_test"` NestedTest *request `json:"nested_test,omitempty"`
Name string `json:"name"` Name string `json:"name,omitempty"`
Field1 string `json:"field1"` Field1 string `json:"field1,omitempty"`
ClientID string ClientID string `json:",omitempty"`
Field2 string Field2 string `json:",omitempty"`
Field3 int64 Field3 int64 `json:",omitempty"`
} }
func TestNestedPath(t *testing.T) { func TestNestedPath(t *testing.T) {
@ -25,10 +43,14 @@ func TestNestedPath(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if s := u.String(); s != "/api/v1/first/second?field1=fieldval" { if s := u.String(); s != "/api/v1/first/second" {
t.Fatalf("nested path error %s", s) t.Fatalf("nested path error %s", s)
} }
_ = m 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) {

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", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
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.Errorf(ctx, "failed to read body: %v", err) log.Error(ctx, "failed to read body", err)
} }
return errors.InternalServerError("go.micro.client", string(buf)) return errors.InternalServerError("go.micro.client", "%s", buf)
} }
} }
if log.V(logger.DebugLevel) { if log.V(logger.DebugLevel) {
log.Debugf(ctx, "response %s with %v", buf, hrsp.Header) log.Debug(ctx, fmt.Sprintf("response %s with %v", buf, hrsp.Header))
} }
if hrsp.StatusCode < 400 { if hrsp.StatusCode < 400 {
if err = cf.Unmarshal(buf, rsp); err != nil { if err = cf.Unmarshal(buf, rsp); err != nil {
return errors.InternalServerError("go.micro.client", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
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", cerr.Error()) return errors.InternalServerError("go.micro.client", "%+v", cerr)
} }
if err, ok = rerr.(error); !ok { if err, ok = rerr.(error); !ok {

33
util.go
View File

@ -195,24 +195,23 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
cleanPath[strings.Join(clean, ".")] = true cleanPath[strings.Join(clean, ".")] = true
} }
} }
if (body == "*" || body == t.name) && method != http.MethodGet {
if tnmsg.Field(i).CanSet() {
tnmsg.Field(i).Set(val)
}
}
for k := range cleanPath { for k := range cleanPath {
if err = rutil.ZeroFieldByPath(nmsg, k); err != nil { if err = rutil.ZeroFieldByPath(nmsg, k); err != nil {
return "", nil, err return "", nil, err
} }
} }
if (body == "*" || body == t.name) && method != http.MethodGet {
if val.Type().Kind() == reflect.Slice { if tnmsg.Field(i).CanSet() {
for idx := 0; idx < val.Len(); idx++ { tnmsg.Field(i).Set(val)
values.Add(t.name, getParam(val.Index(idx))) }
} else if method == http.MethodGet {
if val.Type().Kind() == reflect.Slice {
for idx := 0; idx < val.Len(); idx++ {
values.Add(t.name, getParam(val.Index(idx)))
}
} else if !rutil.IsEmpty(val) {
values.Add(t.name, getParam(val))
} }
} else if !rutil.IsEmpty(val) {
values.Add(t.name, getParam(val))
} }
} }
@ -266,6 +265,8 @@ 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) && !isEmptyStruct(nmsg) { if rutil.IsZero(nmsg) && !isEmptyStruct(nmsg) {
return b.String(), nil, nil return b.String(), nil, nil
} }
@ -333,7 +334,7 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
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.Error(ctx, "failed to read body", err)
} }
return errors.InternalServerError("go.micro.client", string(buf)) return errors.InternalServerError("go.micro.client", "%s", buf)
} }
} }
@ -342,7 +343,7 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
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.Debug(ctx, fmt.Sprintf("response with %v unknown content-type %s %s", hrsp.Header, ct, buf))
} }
return errors.InternalServerError("go.micro.client", cerr.Error()) return errors.InternalServerError("go.micro.client", "%+v", cerr)
} }
if h.opts.Logger.V(logger.DebugLevel) { if h.opts.Logger.V(logger.DebugLevel) {
@ -352,7 +353,7 @@ func (h *httpClient) parseRsp(ctx context.Context, hrsp *http.Response, rsp inte
// 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", err.Error()) return errors.InternalServerError("go.micro.client", "%+v", err)
} }
return nil return nil
} }
@ -372,7 +373,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", cerr.Error()) return errors.InternalServerError("go.micro.client", "%+v", cerr)
} }
if err, ok = rerr.(error); !ok { if err, ok = rerr.(error); !ok {

View File

@ -1,6 +1,7 @@
package http package http
import ( import (
"net/http"
"net/url" "net/url"
"testing" "testing"
) )
@ -52,10 +53,16 @@ func TestNewPathRequest(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
vals := u.Query() switch m {
if v, ok := vals["name"]; !ok || v[0] != "test_name" { case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
t.Fatalf("invalid path: %v nmsg: %v", path, nmsg) break
case http.MethodGet:
vals := u.Query()
if v, ok := vals["name"]; !ok || v[0] != "test_name" {
t.Fatalf("%s invalid path: %v nmsg: %v", m, path, nmsg)
}
} }
} }
} }