Compare commits
26 Commits
Author | SHA1 | Date | |
---|---|---|---|
6a30a4f408 | |||
f80e6c1a66 | |||
2aa8768aed | |||
0ab763b505 | |||
68b6f6904b | |||
31e996fc2e | |||
14f3b149e4 | |||
6714e48f4f | |||
547199f0b8 | |||
|
be637e8324 | ||
67e9e7e880 | |||
|
8a6a259404 | ||
2b3e1acd22 | |||
|
2816fd756a | ||
5353c56034 | |||
|
b93dcbb165 | ||
d76f9f20b6 | |||
|
4cb133546d | ||
c0ca60b7c9 | |||
|
7a096d6605 | ||
1c5c86668b | |||
|
e7b5a90b5c | ||
677f00c3c0 | |||
7365c5f1cd | |||
505c59ba75 | |||
7a39d86018 |
21
.github/workflows/codeql-analysis.yml
vendored
21
.github/workflows/codeql-analysis.yml
vendored
@@ -9,7 +9,7 @@
|
|||||||
# the `language` matrix defined below to confirm you have the correct set of
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
# supported CodeQL languages.
|
# supported CodeQL languages.
|
||||||
#
|
#
|
||||||
name: "CodeQL"
|
name: "codeql"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@@ -17,16 +17,16 @@ on:
|
|||||||
types:
|
types:
|
||||||
- completed
|
- completed
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '34 1 * * 0'
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: Analyze
|
name: analyze
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
actions: read
|
actions: read
|
||||||
@@ -42,11 +42,14 @@ jobs:
|
|||||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.16
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: init
|
||||||
uses: github/codeql-action/init@v1
|
uses: github/codeql-action/init@v1
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
@@ -57,7 +60,7 @@ jobs:
|
|||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: Autobuild
|
- name: autobuild
|
||||||
uses: github/codeql-action/autobuild@v1
|
uses: github/codeql-action/autobuild@v1
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
@@ -71,5 +74,5 @@ jobs:
|
|||||||
# make bootstrap
|
# make bootstrap
|
||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: analyze
|
||||||
uses: github/codeql-action/analyze@v1
|
uses: github/codeql-action/analyze@v1
|
||||||
|
75
.github/workflows/dependabot-automerge.yml
vendored
75
.github/workflows/dependabot-automerge.yml
vendored
@@ -1,66 +1,31 @@
|
|||||||
name: "prautomerge"
|
name: "prautomerge"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
pull_request_target:
|
||||||
workflows: ["prbuild"]
|
types: [assigned, opened, synchronize, reopened]
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Dependabot-Automerge:
|
dependabot:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
# Contains workaround to execute if dependabot updates the PR by checking for the base branch in the linked PR
|
if: ${{ github.actor == 'dependabot[bot]' }}
|
||||||
# The the github.event.workflow_run.event value is 'push' and not 'pull_request'
|
|
||||||
# dont work with multiple workflows when last returns success
|
|
||||||
if: >-
|
|
||||||
github.event.workflow_run.conclusion == 'success'
|
|
||||||
&& github.actor == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.login == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.type == 'Bot'
|
|
||||||
&& (github.event.workflow_run.event == 'pull_request'
|
|
||||||
|| (github.event.workflow_run.event == 'push' && github.event.workflow_run.pull_requests[0].base.ref == github.event.repository.default_branch ))
|
|
||||||
steps:
|
steps:
|
||||||
- name: Approve Changes and Merge changes if label 'dependencies' is set
|
- name: metadata
|
||||||
uses: actions/github-script@v5
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v1.1.1
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: "${{ secrets.TOKEN }}"
|
||||||
script: |
|
- name: approve
|
||||||
console.log(context.payload.workflow_run);
|
run: gh pr review --approve "$PR_URL"
|
||||||
|
env:
|
||||||
var labelNames = await github.paginate(
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
github.issues.listLabelsOnIssue,
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
{
|
- name: merge
|
||||||
repo: context.repo.repo,
|
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||||
owner: context.repo.owner,
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
issue_number: context.payload.workflow_run.pull_requests[0].number,
|
env:
|
||||||
},
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
(response) => response.data.map(
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
(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');
|
|
||||||
}
|
|
||||||
|
6
go.mod
6
go.mod
@@ -1,8 +1,8 @@
|
|||||||
module github.com/unistack-org/micro-server-http/v3
|
module go.unistack.org/micro-server-http/v3
|
||||||
|
|
||||||
go 1.16
|
go 1.16
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/unistack-org/micro/v3 v3.7.6
|
go.unistack.org/micro/v3 v3.8.18
|
||||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b
|
golang.org/x/net v0.0.0-20220121210141-e204ce36a2ba
|
||||||
)
|
)
|
||||||
|
22
go.sum
22
go.sum
@@ -1,22 +1,30 @@
|
|||||||
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/golang-jwt/jwt/v4 v4.1.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
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 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
|
||||||
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 h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||||
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-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
github.com/silas/dag v0.0.0-20211117232152-9d50aa809f35/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||||
github.com/unistack-org/micro-proto v0.0.9 h1:KrWLS4FUX7UAWNAilQf70uad6ZPf/0EudeddCXllRVc=
|
go.unistack.org/micro-proto/v3 v3.1.1 h1:78qRmltwGek5kSQ9tNmDZ9TCRvZM7YDIOgzriKvabjA=
|
||||||
github.com/unistack-org/micro-proto v0.0.9/go.mod h1:Cckwmzd89gvS7ThxzZp9kQR/EOdksFQcsTAtDDyKwrg=
|
go.unistack.org/micro-proto/v3 v3.1.1/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
|
||||||
github.com/unistack-org/micro/v3 v3.7.6 h1:cobNkaicZR+8nbDWRUmX3/CSLh6ZNSytK2zWth4s4IM=
|
go.unistack.org/micro/v3 v3.8.18 h1:+7UiB46D9EoCgGN+JfhoWCvn36yvtplh6fmA1+ZiqEE=
|
||||||
github.com/unistack-org/micro/v3 v3.7.6/go.mod h1:Ke/8WJlNZi4ZYwL9HcsANAbQ66/HocTBEZM+od99/mM=
|
go.unistack.org/micro/v3 v3.8.18/go.mod h1:ueDiiOe3fRW9kL0Fbh4OWw/R/SQhMd6vUcAV/WHYRWw=
|
||||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b h1:eB48h3HiRycXNy8E0Gf5e0hv7YT6Kt14L/D73G1fuwo=
|
|
||||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.0.0-20220121175114-2ed6ce1e1725 h1:YtkHkox9J+kfAdNdlvEXp2SkLMQSkSjWFP4sjgxEPa8=
|
||||||
|
golang.org/x/net v0.0.0-20220121175114-2ed6ce1e1725/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||||
|
golang.org/x/net v0.0.0-20220121210141-e204ce36a2ba h1:6u6sik+bn/y7vILcYkK3iwTBWN7WtBvB0+SZswQnbf8=
|
||||||
|
golang.org/x/net v0.0.0-20220121210141-e204ce36a2ba/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
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/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
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/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
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-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 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||||
|
97
handler.go
97
handler.go
@@ -9,13 +9,13 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/errors"
|
"go.unistack.org/micro/v3/errors"
|
||||||
"github.com/unistack-org/micro/v3/logger"
|
"go.unistack.org/micro/v3/logger"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
"github.com/unistack-org/micro/v3/register"
|
"go.unistack.org/micro/v3/register"
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
rhttp "github.com/unistack-org/micro/v3/util/http"
|
rhttp "go.unistack.org/micro/v3/util/http"
|
||||||
rflutil "github.com/unistack-org/micro/v3/util/reflect"
|
rflutil "go.unistack.org/micro/v3/util/reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -32,13 +32,12 @@ type patHandler struct {
|
|||||||
mtype *methodType
|
mtype *methodType
|
||||||
rcvr reflect.Value
|
rcvr reflect.Value
|
||||||
name string
|
name string
|
||||||
pat *rhttp.Trie
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type httpHandler struct {
|
type httpHandler struct {
|
||||||
opts server.HandlerOptions
|
opts server.HandlerOptions
|
||||||
hd interface{}
|
hd interface{}
|
||||||
handlers map[string][]patHandler
|
handlers *rhttp.Trie
|
||||||
name string
|
name string
|
||||||
eps []*register.Endpoint
|
eps []*register.Endpoint
|
||||||
sopts server.Options
|
sopts server.Options
|
||||||
@@ -62,27 +61,21 @@ func (h *httpHandler) Options() server.HandlerOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// check for http.HandlerFunc handlers
|
||||||
if ph, _, ok := h.pathHandlers.Search(r.Method, r.URL.Path); ok {
|
if ph, _, ok := h.pathHandlers.Search(r.Method, r.URL.Path); ok {
|
||||||
ph.(http.HandlerFunc)(w, r)
|
ph.(http.HandlerFunc)(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ct := DefaultContentType
|
ct := DefaultContentType
|
||||||
if htype := r.Header.Get("Content-Type"); htype != "" {
|
if htype := r.Header.Get(metadata.HeaderContentType); htype != "" {
|
||||||
ct = htype
|
ct = htype
|
||||||
}
|
}
|
||||||
|
|
||||||
if idx := strings.Index(ct, ":"); idx > 0 {
|
|
||||||
if ph, ok := h.contentTypeHandlers[ct[:idx]]; ok {
|
|
||||||
ph(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{})
|
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{})
|
||||||
md, ok := metadata.FromIncomingContext(ctx)
|
md, ok := metadata.FromIncomingContext(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
md = metadata.New(len(r.Header))
|
md = metadata.New(len(r.Header) + 8)
|
||||||
}
|
}
|
||||||
for k, v := range r.Header {
|
for k, v := range r.Header {
|
||||||
md.Set(k, strings.Join(v, ", "))
|
md.Set(k, strings.Join(v, ", "))
|
||||||
@@ -101,7 +94,7 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
path := r.URL.Path
|
path := r.URL.Path
|
||||||
if !strings.HasPrefix(path, "/") {
|
if !strings.HasPrefix(path, "/") {
|
||||||
h.errorHandler(ctx, nil, w, r, fmt.Errorf("path must contains /"), http.StatusBadRequest)
|
h.errorHandler(ctx, nil, w, r, fmt.Errorf("path must starts with /"), http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,28 +107,29 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
matches := make(map[string]interface{})
|
matches := make(map[string]interface{})
|
||||||
|
|
||||||
var match bool
|
var match bool
|
||||||
var hldr patHandler
|
var hldr *patHandler
|
||||||
var handler *httpHandler
|
var handler *httpHandler
|
||||||
|
|
||||||
fmt.Printf("try to find handler\n")
|
for _, shdlr := range h.handlers {
|
||||||
for _, hpat := range h.handlers {
|
hdlr := shdlr.(*httpHandler)
|
||||||
handlertmp := hpat.(*httpHandler)
|
fh, mp, ok := hdlr.handlers.Search(r.Method, path)
|
||||||
for _, hldrtmp := range handlertmp.handlers[r.Method] {
|
if ok {
|
||||||
fmt.Printf("ssss method %v path %v %#+v\n", r.Method, path, hldrtmp)
|
match = true
|
||||||
_, mp, ok := hldrtmp.pat.Search(r.Method, path)
|
for k, v := range mp {
|
||||||
if ok {
|
matches[k] = v
|
||||||
match = true
|
|
||||||
for k, v := range mp {
|
|
||||||
matches[k] = v
|
|
||||||
}
|
|
||||||
hldr = hldrtmp
|
|
||||||
handler = handlertmp
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
hldr = fh.(*patHandler)
|
||||||
|
handler = hdlr
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !match {
|
if !match && h.hd != nil {
|
||||||
|
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
||||||
|
hdlr.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else if !match {
|
||||||
h.errorHandler(ctx, nil, w, r, fmt.Errorf("not matching route found"), http.StatusNotFound)
|
h.errorHandler(ctx, nil, w, r, fmt.Errorf("not matching route found"), http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -171,32 +165,31 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
replyv = reflect.New(hldr.mtype.ReplyType.Elem())
|
replyv = reflect.New(hldr.mtype.ReplyType.Elem())
|
||||||
|
|
||||||
function := hldr.mtype.method.Func
|
function := hldr.mtype.method.Func
|
||||||
// function := hldr.rcvr
|
|
||||||
var returnValues []reflect.Value
|
var returnValues []reflect.Value
|
||||||
|
|
||||||
if err = cf.ReadBody(r.Body, argv.Interface()); err != nil && err != io.EOF {
|
buf, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
h.errorHandler(ctx, handler, w, r, err, http.StatusInternalServerError)
|
h.errorHandler(ctx, handler, w, r, err, http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err = cf.Unmarshal(buf, argv.Interface()); err != nil {
|
||||||
|
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
matches = rflutil.FlattenMap(matches)
|
matches = rflutil.FlattenMap(matches)
|
||||||
if err = rflutil.Merge(argv.Interface(), matches, rflutil.SliceAppend(true), rflutil.Tags([]string{"protobuf", "json"})); err != nil {
|
if err = rflutil.Merge(argv.Interface(), matches, rflutil.SliceAppend(true), rflutil.Tags([]string{"protobuf", "json"})); err != nil {
|
||||||
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := cf.Marshal(argv.Interface())
|
|
||||||
if err != nil {
|
|
||||||
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hr := &rpcRequest{
|
hr := &rpcRequest{
|
||||||
codec: cf,
|
codec: cf,
|
||||||
service: handler.sopts.Name,
|
service: handler.sopts.Name,
|
||||||
contentType: ct,
|
contentType: ct,
|
||||||
method: fmt.Sprintf("%s.%s", hldr.name, hldr.mtype.method.Name),
|
method: fmt.Sprintf("%s.%s", hldr.name, hldr.mtype.method.Name),
|
||||||
body: b,
|
body: buf,
|
||||||
payload: argv.Interface(),
|
payload: argv.Interface(),
|
||||||
header: md,
|
header: md,
|
||||||
}
|
}
|
||||||
@@ -241,13 +234,13 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
scode := int(200)
|
scode := int(200)
|
||||||
appErr := fn(ctx, hr, replyv.Interface())
|
appErr := fn(ctx, hr, replyv.Interface())
|
||||||
|
|
||||||
w.Header().Set("Content-Type", ct)
|
w.Header().Set(metadata.HeaderContentType, ct)
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
w.Header().Set(k, v)
|
w.Header().Set(k, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if nct := w.Header().Get("Content-Type"); nct != ct {
|
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
|
||||||
if cf, err = h.newCodec(nct); err != nil {
|
if cf, err = h.newCodec(nct); err != nil {
|
||||||
h.errorHandler(ctx, nil, w, r, err, http.StatusBadRequest)
|
h.errorHandler(ctx, nil, w, r, err, http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
@@ -258,14 +251,14 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
switch verr := appErr.(type) {
|
switch verr := appErr.(type) {
|
||||||
case *errors.Error:
|
case *errors.Error:
|
||||||
scode = int(verr.Code)
|
scode = int(verr.Code)
|
||||||
b, err = cf.Marshal(verr)
|
buf, err = cf.Marshal(verr)
|
||||||
case *Error:
|
case *Error:
|
||||||
b, err = cf.Marshal(verr.err)
|
buf, err = cf.Marshal(verr.err)
|
||||||
default:
|
default:
|
||||||
b, err = cf.Marshal(appErr)
|
buf, err = cf.Marshal(appErr)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
b, err = cf.Marshal(replyv.Interface())
|
buf, err = cf.Marshal(replyv.Interface())
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
||||||
@@ -278,7 +271,7 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
w.WriteHeader(scode)
|
w.WriteHeader(scode)
|
||||||
|
|
||||||
if _, cerr := w.Write(b); cerr != nil {
|
if _, cerr := w.Write(buf); cerr != nil {
|
||||||
logger.DefaultLogger.Errorf(ctx, "write failed: %v", cerr)
|
handler.sopts.Logger.Errorf(ctx, "write failed: %v", cerr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
106
http.go
106
http.go
@@ -1,5 +1,5 @@
|
|||||||
// Package http implements a go-micro.Server
|
// Package http implements a go-micro.Server
|
||||||
package http
|
package http // import "go.unistack.org/micro-server-http/v3"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -13,38 +13,27 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/logger"
|
"go.unistack.org/micro/v3/logger"
|
||||||
"github.com/unistack-org/micro/v3/register"
|
"go.unistack.org/micro/v3/register"
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
rhttp "github.com/unistack-org/micro/v3/util/http"
|
rhttp "go.unistack.org/micro/v3/util/http"
|
||||||
"golang.org/x/net/netutil"
|
"golang.org/x/net/netutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
var httpAllMethods = []string{
|
var _ server.Server = &httpServer{}
|
||||||
http.MethodConnect,
|
|
||||||
http.MethodDelete,
|
|
||||||
http.MethodGet,
|
|
||||||
http.MethodHead,
|
|
||||||
http.MethodOptions,
|
|
||||||
http.MethodPatch,
|
|
||||||
http.MethodPost,
|
|
||||||
http.MethodPut,
|
|
||||||
http.MethodTrace,
|
|
||||||
}
|
|
||||||
|
|
||||||
type httpServer struct {
|
type httpServer struct {
|
||||||
hd server.Handler
|
hd server.Handler
|
||||||
rsvc *register.Service
|
rsvc *register.Service
|
||||||
handlers map[string]server.Handler
|
handlers map[string]server.Handler
|
||||||
exit chan chan error
|
exit chan chan error
|
||||||
subscribers map[*httpSubscriber][]broker.Subscriber
|
subscribers map[*httpSubscriber][]broker.Subscriber
|
||||||
errorHandler func(context.Context, server.Handler, http.ResponseWriter, *http.Request, error, int)
|
errorHandler func(context.Context, server.Handler, http.ResponseWriter, *http.Request, error, int)
|
||||||
pathHandlers *rhttp.Trie
|
pathHandlers *rhttp.Trie
|
||||||
contentTypeHandlers map[string]http.HandlerFunc
|
opts server.Options
|
||||||
opts server.Options
|
registerRPC bool
|
||||||
registerRPC bool
|
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
registered bool
|
registered bool
|
||||||
init bool
|
init bool
|
||||||
@@ -89,22 +78,19 @@ func (h *httpServer) Init(opts ...server.Option) error {
|
|||||||
if h.pathHandlers == nil {
|
if h.pathHandlers == nil {
|
||||||
h.pathHandlers = rhttp.NewTrie()
|
h.pathHandlers = rhttp.NewTrie()
|
||||||
}
|
}
|
||||||
if h.contentTypeHandlers == nil {
|
|
||||||
h.contentTypeHandlers = make(map[string]http.HandlerFunc)
|
|
||||||
}
|
|
||||||
|
|
||||||
if v, ok := h.opts.Context.Value(registerRPCHandlerKey{}).(bool); ok {
|
if v, ok := h.opts.Context.Value(registerRPCHandlerKey{}).(bool); ok {
|
||||||
h.registerRPC = v
|
h.registerRPC = v
|
||||||
}
|
}
|
||||||
|
|
||||||
if phs, ok := h.opts.Context.Value(pathHandlerKey{}).(*pathHandlerVal); ok && phs.h != nil {
|
if phs, ok := h.opts.Context.Value(pathHandlerKey{}).(*pathHandlerVal); ok && phs.h != nil {
|
||||||
for pp, ph := range phs.h {
|
for pm, ps := range phs.h {
|
||||||
h.pathHandlers.Insert(httpAllMethods, pp, ph)
|
for pp, ph := range ps {
|
||||||
}
|
if err := h.pathHandlers.Insert([]string{pm}, pp, ph); err != nil {
|
||||||
}
|
h.Unlock()
|
||||||
if phs, ok := h.opts.Context.Value(contentTypeHandlerKey{}).(*contentTypeHandlerVal); ok && phs.h != nil {
|
return err
|
||||||
for pp, ph := range phs.h {
|
}
|
||||||
h.contentTypeHandlers[pp] = ph
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
h.Unlock()
|
h.Unlock()
|
||||||
@@ -148,6 +134,7 @@ func (h *httpServer) Init(opts ...server.Option) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpServer) Handle(handler server.Handler) error {
|
func (h *httpServer) Handle(handler server.Handler) error {
|
||||||
|
// passed unknown handler
|
||||||
hdlr, ok := handler.(*httpHandler)
|
hdlr, ok := handler.(*httpHandler)
|
||||||
if !ok {
|
if !ok {
|
||||||
h.Lock()
|
h.Lock()
|
||||||
@@ -156,6 +143,7 @@ func (h *httpServer) Handle(handler server.Handler) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// passed http.Handler like some muxer
|
||||||
if _, ok := hdlr.hd.(http.Handler); ok {
|
if _, ok := hdlr.hd.(http.Handler); ok {
|
||||||
h.Lock()
|
h.Lock()
|
||||||
h.hd = handler
|
h.hd = handler
|
||||||
@@ -163,6 +151,7 @@ func (h *httpServer) Handle(handler server.Handler) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// passed micro compat handler
|
||||||
h.Lock()
|
h.Lock()
|
||||||
if h.handlers == nil {
|
if h.handlers == nil {
|
||||||
h.handlers = make(map[string]server.Handler)
|
h.handlers = make(map[string]server.Handler)
|
||||||
@@ -185,20 +174,16 @@ func (h *httpServer) NewHandler(handler interface{}, opts ...server.HandlerOptio
|
|||||||
}
|
}
|
||||||
|
|
||||||
hdlr := &httpHandler{
|
hdlr := &httpHandler{
|
||||||
eps: eps,
|
eps: eps,
|
||||||
hd: handler,
|
hd: handler,
|
||||||
opts: options,
|
opts: options,
|
||||||
sopts: h.opts,
|
sopts: h.opts,
|
||||||
|
handlers: rhttp.NewTrie(),
|
||||||
}
|
}
|
||||||
|
|
||||||
tp := reflect.TypeOf(handler)
|
tp := reflect.TypeOf(handler)
|
||||||
type nilHandler struct{}
|
|
||||||
|
|
||||||
hdlr.handlers = make(map[string][]patHandler)
|
|
||||||
for hn, md := range options.Metadata {
|
for hn, md := range options.Metadata {
|
||||||
pat := rhttp.NewTrie()
|
|
||||||
pat.Insert([]string{md["Method"]}, md["Path"], &nilHandler{})
|
|
||||||
|
|
||||||
var method reflect.Method
|
var method reflect.Method
|
||||||
mname := hn[strings.Index(hn, ".")+1:]
|
mname := hn[strings.Index(hn, ".")+1:]
|
||||||
for m := 0; m < tp.NumMethod(); m++ {
|
for m := 0; m < tp.NumMethod(); m++ {
|
||||||
@@ -220,25 +205,25 @@ func (h *httpServer) NewHandler(handler interface{}, opts ...server.HandlerOptio
|
|||||||
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
|
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
|
||||||
continue
|
continue
|
||||||
} else if mtype == nil {
|
} else if mtype == nil {
|
||||||
|
h.opts.Logger.Errorf(h.opts.Context, "nil mtype for %s", mname)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
rcvr := reflect.ValueOf(handler)
|
rcvr := reflect.ValueOf(handler)
|
||||||
name := reflect.Indirect(rcvr).Type().Name()
|
name := reflect.Indirect(rcvr).Type().Name()
|
||||||
|
|
||||||
pth := patHandler{pat: pat, mtype: mtype, name: name, rcvr: rcvr}
|
pth := &patHandler{mtype: mtype, name: name, rcvr: rcvr}
|
||||||
hdlr.name = name
|
hdlr.name = name
|
||||||
hdlr.handlers[md["Method"]] = append(hdlr.handlers[md["Method"]], pth)
|
|
||||||
|
|
||||||
if !h.registerRPC {
|
if err := hdlr.handlers.Insert([]string{md["Method"]}, md["Path"], pth); err != nil {
|
||||||
continue
|
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md["Method"], md["Path"])
|
||||||
}
|
}
|
||||||
|
|
||||||
rpat := rhttp.NewTrie()
|
if h.registerRPC {
|
||||||
rpat.Insert([]string{http.MethodPost}, "/"+hn, &nilHandler{})
|
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
|
||||||
|
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md["Method"], md["Path"])
|
||||||
pth = patHandler{pat: rpat, mtype: mtype, name: name, rcvr: rcvr}
|
}
|
||||||
hdlr.handlers[http.MethodPost] = append(hdlr.handlers[http.MethodPost], pth)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return hdlr
|
return hdlr
|
||||||
@@ -465,9 +450,12 @@ func (h *httpServer) Start() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if handler == nil && h.hd == nil {
|
switch {
|
||||||
|
case handler == nil && h.hd == nil:
|
||||||
handler = h
|
handler = h
|
||||||
} else if handler == nil && h.hd != nil {
|
case len(h.handlers) > 0 && h.hd != nil:
|
||||||
|
handler = h
|
||||||
|
case handler == nil && h.hd != nil:
|
||||||
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
||||||
handler = hdlr
|
handler = hdlr
|
||||||
}
|
}
|
||||||
@@ -602,7 +590,7 @@ func (h *httpServer) Name() string {
|
|||||||
return h.opts.Name
|
return h.opts.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(opts ...server.Option) server.Server {
|
func NewServer(opts ...server.Option) *httpServer {
|
||||||
options := server.NewOptions(opts...)
|
options := server.NewOptions(opts...)
|
||||||
return &httpServer{
|
return &httpServer{
|
||||||
opts: options,
|
opts: options,
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpMessage struct {
|
type httpMessage struct {
|
||||||
|
56
options.go
56
options.go
@@ -5,7 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SetError pass error to caller
|
// SetError pass error to caller
|
||||||
@@ -78,44 +78,27 @@ func ErrorHandler(fn func(ctx context.Context, s server.Handler, w http.Response
|
|||||||
type (
|
type (
|
||||||
pathHandlerKey struct{}
|
pathHandlerKey struct{}
|
||||||
pathHandlerVal struct {
|
pathHandlerVal struct {
|
||||||
h map[string]http.HandlerFunc
|
h map[string]map[string]http.HandlerFunc
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// PathHandler specifies http handler for path regexp
|
// PathHandler specifies http handler for path regexp
|
||||||
func PathHandler(path string, h http.HandlerFunc) server.Option {
|
func PathHandler(method, path string, handler http.HandlerFunc) server.Option {
|
||||||
return func(o *server.Options) {
|
return func(o *server.Options) {
|
||||||
if o.Context == nil {
|
if o.Context == nil {
|
||||||
o.Context = context.Background()
|
o.Context = context.Background()
|
||||||
}
|
}
|
||||||
v, ok := o.Context.Value(pathHandlerKey{}).(*pathHandlerVal)
|
v, ok := o.Context.Value(pathHandlerKey{}).(*pathHandlerVal)
|
||||||
if !ok {
|
if !ok {
|
||||||
v = &pathHandlerVal{h: make(map[string]http.HandlerFunc)}
|
v = &pathHandlerVal{h: make(map[string]map[string]http.HandlerFunc)}
|
||||||
}
|
}
|
||||||
v.h[path] = h
|
m, ok := v.h[method]
|
||||||
o.Context = context.WithValue(o.Context, pathHandlerKey{}, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
|
||||||
contentTypeHandlerKey struct{}
|
|
||||||
contentTypeHandlerVal struct {
|
|
||||||
h map[string]http.HandlerFunc
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// ContentTypeHandler specifies http handler for Content-Type
|
|
||||||
func ContentTypeHandler(ct string, h http.HandlerFunc) server.Option {
|
|
||||||
return func(o *server.Options) {
|
|
||||||
if o.Context == nil {
|
|
||||||
o.Context = context.Background()
|
|
||||||
}
|
|
||||||
v, ok := o.Context.Value(contentTypeHandlerKey{}).(*contentTypeHandlerVal)
|
|
||||||
if !ok {
|
if !ok {
|
||||||
v = &contentTypeHandlerVal{h: make(map[string]http.HandlerFunc)}
|
m = make(map[string]http.HandlerFunc)
|
||||||
|
v.h[method] = m
|
||||||
}
|
}
|
||||||
v.h[ct] = h
|
m[path] = handler
|
||||||
o.Context = context.WithValue(o.Context, contentTypeHandlerKey{}, v)
|
o.Context = context.WithValue(o.Context, pathHandlerKey{}, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,3 +108,24 @@ type registerRPCHandlerKey struct{}
|
|||||||
func RegisterRPCHandler(b bool) server.Option {
|
func RegisterRPCHandler(b bool) server.Option {
|
||||||
return server.SetOption(registerRPCHandlerKey{}, b)
|
return server.SetOption(registerRPCHandlerKey{}, b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type headerKey struct{}
|
||||||
|
|
||||||
|
type handlerOptions struct {
|
||||||
|
headers []string
|
||||||
|
cookies []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type FillRequestOption func(*handlerOptions)
|
||||||
|
|
||||||
|
func Header(headers ...string) FillRequestOption {
|
||||||
|
return func(o *handlerOptions) {
|
||||||
|
o.headers = append(o.headers, headers...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Cookie(cookies ...string) FillRequestOption {
|
||||||
|
return func(o *handlerOptions) {
|
||||||
|
o.cookies = append(o.cookies, cookies...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -3,9 +3,9 @@ package http
|
|||||||
import (
|
import (
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@@ -7,7 +7,7 @@ import (
|
|||||||
"unicode"
|
"unicode"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
type methodType struct {
|
type methodType struct {
|
||||||
|
@@ -7,11 +7,11 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/unistack-org/micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"github.com/unistack-org/micro/v3/codec"
|
"go.unistack.org/micro/v3/codec"
|
||||||
"github.com/unistack-org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
"github.com/unistack-org/micro/v3/register"
|
"go.unistack.org/micro/v3/register"
|
||||||
"github.com/unistack-org/micro/v3/server"
|
"go.unistack.org/micro/v3/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
|
var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
|
||||||
|
55
util.go
Normal file
55
util.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
func FillRequest(ctx context.Context, req interface{}, opts ...FillRequestOption) error {
|
||||||
|
var err error
|
||||||
|
options := handlerOptions{}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&options)
|
||||||
|
}
|
||||||
|
md, ok := metadata.FromIncomingContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for idx := 0; idx < len(options.headers)/2; idx += 2 {
|
||||||
|
k := http.CanonicalHeaderKey(options.headers[idx])
|
||||||
|
v, ok := md[k]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = rutil.SetFieldByPath(req, v, k); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cookies := strings.Split(md["Cookie"], ";")
|
||||||
|
cmd := make(map[string]string, len(cookies))
|
||||||
|
for _, cookie := range cookies {
|
||||||
|
kv := strings.Split(cookie, "=")
|
||||||
|
if len(kv) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cmd[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
|
||||||
|
}
|
||||||
|
for idx := 0; idx < len(options.cookies)/2; idx += 2 {
|
||||||
|
k := http.CanonicalHeaderKey(options.cookies[idx])
|
||||||
|
v, ok := cmd[k]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = rutil.SetFieldByPath(req, v, k); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
56
util_test.go
Normal file
56
util_test.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFillrequest(t *testing.T) {
|
||||||
|
md := metadata.New(1)
|
||||||
|
md.Set("ClientID", "xxx")
|
||||||
|
type request struct {
|
||||||
|
Token string
|
||||||
|
ClientID string
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
hreq, _ := http.NewRequestWithContext(ctx, http.MethodGet, "/v1", nil)
|
||||||
|
cookie1 := &http.Cookie{Name: "Token", Value: "zzz"}
|
||||||
|
cookie2 := &http.Cookie{Name: "Token", Value: "zzz"}
|
||||||
|
hreq.AddCookie(cookie1)
|
||||||
|
hreq.AddCookie(cookie2)
|
||||||
|
|
||||||
|
buf := bytes.NewBuffer(nil)
|
||||||
|
_ = hreq.Write(buf)
|
||||||
|
var cookie string
|
||||||
|
var line string
|
||||||
|
var err error
|
||||||
|
for {
|
||||||
|
line, err = buf.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if strings.Contains(line, "Cookie") {
|
||||||
|
cookie = strings.TrimSpace(strings.Split(line, ":")[1])
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
md.Set("Cookie", cookie)
|
||||||
|
ctx = metadata.NewIncomingContext(ctx, md)
|
||||||
|
req := &request{}
|
||||||
|
|
||||||
|
if err := FillRequest(ctx, req, Cookie("Token", "true"), Header("ClientID", "true")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if req.ClientID != "xxx" {
|
||||||
|
t.Fatalf("FillRequest error: %#+v", req)
|
||||||
|
}
|
||||||
|
if req.Token != "zzz" {
|
||||||
|
t.Fatalf("FillRequest error: %#+v", req)
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user