Compare commits
222 Commits
v3.0.0-alp
...
v3.0.0-del
| Author | SHA1 | Date | |
|---|---|---|---|
| 6dc7e792c8 | |||
| 81649d51e1 | |||
| 23f5d10ccb | |||
| e3f235acc1 | |||
| fa9ef1c816 | |||
| 77dab8ee15 | |||
| 51fbff3e4a | |||
| bd6493327f | |||
|
|
2141e9631c | ||
| be8d09c663 | |||
| 72bbbe3817 | |||
| c92add984c | |||
| 3542d6c824 | |||
| dc63d96e0b | |||
| 7c9a7e84c7 | |||
| 31180758b4 | |||
| ce25a41fe1 | |||
| 8fa8afdfa4 | |||
| e127547799 | |||
| 1fbf8b2e20 | |||
| e41bb5ebc5 | |||
| 7c311aea19 | |||
| 8a2b122015 | |||
| 40b0870cf8 | |||
| e6ab6d50eb | |||
| a9eff06976 | |||
| 416fe5e4c8 | |||
| ddb53bf8e4 | |||
| 0e6efda528 | |||
| f2413a7789 | |||
| 9553f46cf4 | |||
| 14c97d59c1 | |||
| a59aae760f | |||
| 0a5b34a07b | |||
| 62502ad720 | |||
| 6e43ae7190 | |||
| 0e1f744fcc | |||
| 2fc47782cf | |||
| 34d93306d6 | |||
| 336868ed0d | |||
| 2682f15b8e | |||
| 4c12e38c01 | |||
| 62bfe9c06e | |||
| 24be220f91 | |||
| cacd33e84f | |||
| 9475003059 | |||
| 8532ccebba | |||
| 9c55b1d06a | |||
| efd9075d9b | |||
| 4c4fa00a5d | |||
| 21d5ca1cdd | |||
| ec3c1a02fc | |||
| dc5dc6ab5b | |||
| 1cbd1d2bad | |||
| aa667728a1 | |||
| 9b11ea527a | |||
| 5787a1afb8 | |||
| 74c10f1139 | |||
| 7e3fac8937 | |||
| 6021edc855 | |||
| 8817c110d0 | |||
| d59db9df16 | |||
| 2d1e6db9fd | |||
| 5bfca99627 | |||
| 9ea3149b60 | |||
| 8f03480ed2 | |||
| caec730248 | |||
| f1fde75567 | |||
| 5fe3a46732 | |||
| e7d418183b | |||
| c576749b57 | |||
| c062aab1a9 | |||
| 0252addf05 | |||
| b7338c12d7 | |||
| 7c115823a7 | |||
| 47d007c0b6 | |||
| c9b283be60 | |||
| 112f21006c | |||
| 53654185ba | |||
| 2382446e10 | |||
| 24c20b6907 | |||
| 622490fbf3 | |||
| dd8894e673 | |||
| eb1b14da8a | |||
| 0005f23585 | |||
| fb233374a0 | |||
| 9c695ac343 | |||
| 2c136b005e | |||
| 7cf42589b3 | |||
| 6aa857dfa1 | |||
| 0f19355621 | |||
| aa99378adc | |||
| b4ccde2228 | |||
| 36c53b4917 | |||
| ef773d8d49 | |||
| fc3794f548 | |||
| 67ab44593b | |||
| 8076e410a9 | |||
| dd78ae8658 | |||
| 0f4b1435d9 | |||
| c4a303190a | |||
| 199ff66bd4 | |||
| 98ba3b2788 | |||
| 5ea2590891 | |||
| 0a42845a40 | |||
|
|
e6daa9a838 | ||
|
|
72621e0da4 | ||
|
|
d5da9c0728 | ||
|
|
eee5b98d78 | ||
|
|
cf084b410f | ||
| cf9bdd0f99 | |||
| 06136312bb | |||
| 7a407d5792 | |||
|
|
66df1bb361 | ||
|
|
7eaec450a1 | ||
|
|
5d6b7b3d7d | ||
|
|
2eac8ed64f | ||
|
|
2b2dc2f811 | ||
|
|
21cca297c0 | ||
|
|
19ef225b2f | ||
| 2a23224d91 | |||
|
|
dd2dc7a2b9 | ||
|
|
4413372a3f | ||
|
|
a2a808f2d6 | ||
|
|
7a6669d199 | ||
|
|
09fdd3c121 | ||
|
|
da4159513e | ||
|
|
e1248f90f4 | ||
|
|
3011bad518 | ||
|
|
bb7fe21c46 | ||
|
|
4fd4a116f2 | ||
|
|
50ec6c748f | ||
|
|
7135787b78 | ||
|
|
870a1ebc07 | ||
|
|
61899398b3 | ||
|
|
55d62fc1a5 | ||
|
|
5238a8a85f | ||
|
|
9fffd0419e | ||
|
|
58794df27c | ||
|
|
5a88ea7247 | ||
|
|
374aae1490 | ||
|
|
ccf2f4efd6 | ||
|
|
9380b365de | ||
|
|
f0142febcf | ||
|
|
1fa3ac5599 | ||
|
|
375b67ee16 | ||
|
|
69a53e8070 | ||
|
|
b6e1c7ac99 | ||
|
|
e83a808b05 | ||
|
|
012ec6a998 | ||
|
|
fae4151027 | ||
|
|
e162e6d505 | ||
|
|
c51ef6fc29 | ||
|
|
28d6340f04 | ||
|
|
4fc193f95d | ||
|
|
d072eb6ff2 | ||
|
|
1263806a39 | ||
|
|
959407bad9 | ||
|
|
61d12d3a39 | ||
|
|
4db8ea8f6a | ||
|
|
13f495587e | ||
|
|
593b543230 | ||
|
|
fdce953c15 | ||
|
|
96836f2e43 | ||
|
|
65e6ee8566 | ||
|
|
a7c70c66b1 | ||
|
|
b2582c0992 | ||
|
|
6373cc91b7 | ||
|
|
ed704640aa | ||
|
|
cd9e5a1e9e | ||
|
|
dcf040ec9f | ||
|
|
f838c33008 | ||
|
|
e8ea0f85e9 | ||
|
|
51f8b4ae3d | ||
|
|
69a2032dd7 | ||
|
|
64feb6dff2 | ||
|
|
4c95c65d81 | ||
|
|
4469a41ae7 | ||
|
|
fc67593ee4 | ||
|
|
e7cc3c2210 | ||
|
|
712fe39a62 | ||
|
|
9b14eb8aec | ||
|
|
124b1bd7b7 | ||
|
|
ac1aace214 | ||
|
|
324c4e6886 | ||
|
|
d69a4a30cd | ||
|
|
a6d7b1d710 | ||
|
|
8ee31b94a1 | ||
|
|
37cc7fda92 | ||
|
|
d61cbd29db | ||
|
|
b6ab124d83 | ||
|
|
835343d6a5 | ||
|
|
74907987d1 | ||
|
|
fb8533b74e | ||
|
|
dcf785677f | ||
|
|
991cdba91d | ||
|
|
aefd052dd7 | ||
|
|
2b79910ad9 | ||
|
|
8674dc8e62 | ||
|
|
b93cd0c964 | ||
|
|
39bd6a6ced | ||
|
|
03d47afe47 | ||
|
|
38ec233350 | ||
|
|
eee91ed976 | ||
|
|
07fef9fd33 | ||
|
|
1106f1d996 | ||
|
|
8e126e4fc1 | ||
|
|
1439b101ec | ||
|
|
24e5b2a034 | ||
|
|
971a962894 | ||
|
|
31ed4aa0e8 | ||
|
|
d2cea4b7b7 | ||
|
|
0b73d411ad | ||
|
|
83a64797fb | ||
|
|
e9fc5b1671 | ||
|
|
006bbefaf3 | ||
|
|
3d1ba914fc | ||
|
|
d66803a136 | ||
|
|
9813f98c8b | ||
| c6163bb22f | |||
|
|
cb4a2864da | ||
|
|
f17e4fdb44 |
3
.github/FUNDING.yml
vendored
3
.github/FUNDING.yml
vendored
@@ -1,3 +0,0 @@
|
|||||||
# These are supported funding model platforms
|
|
||||||
|
|
||||||
github: micro
|
|
||||||
2
.github/generate.sh
vendored
2
.github/generate.sh
vendored
@@ -9,7 +9,7 @@ curl -s -o proto/google/api/http.proto -L https://raw.githubusercontent.com/goog
|
|||||||
|
|
||||||
for PROTO in $PROTOS; do
|
for PROTO in $PROTOS; do
|
||||||
echo $PROTO
|
echo $PROTO
|
||||||
protoc -I./proto -I. -I$(dirname $PROTO) --go_out=plugins=grpc,paths=source_relative:. --micro_out=paths=source_relative:. $PROTO
|
protoc -I./proto -I. -I$(dirname $PROTO) --go-grpc_out=paths=source_relative:. --go_out=paths=source_relative:. --micro_out=paths=source_relative:. $PROTO
|
||||||
done
|
done
|
||||||
|
|
||||||
rm -r proto
|
rm -r proto
|
||||||
|
|||||||
13
.github/stale.sh
vendored
Executable file
13
.github/stale.sh
vendored
Executable file
@@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/bash -ex
|
||||||
|
|
||||||
|
export PATH=$PATH:$(pwd)/bin
|
||||||
|
export GO111MODULE=on
|
||||||
|
export GOBIN=$(pwd)/bin
|
||||||
|
|
||||||
|
#go get github.com/rvflash/goup@v0.4.1
|
||||||
|
|
||||||
|
#goup -v ./...
|
||||||
|
#go get github.com/psampaz/go-mod-outdated@v0.6.0
|
||||||
|
go list -u -m -mod=mod -json all | go-mod-outdated -update -direct -ci || true
|
||||||
|
|
||||||
|
#go list -u -m -json all | go-mod-outdated -update
|
||||||
62
.github/workflows/build.yml
vendored
Normal file
62
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
name: build
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v1
|
||||||
|
with:
|
||||||
|
go-version: 1.15
|
||||||
|
- name: cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: ${{ runner.os }}-go-
|
||||||
|
- name: sdk checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
- name: sdk deps
|
||||||
|
run: go get -v -t -d ./...
|
||||||
|
- name: sdk test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: go test -mod readonly -v ./...
|
||||||
|
- name: tests checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
repository: unistack-org/micro-tests
|
||||||
|
ref: refs/heads/master
|
||||||
|
path: micro-tests
|
||||||
|
fetch-depth: 1
|
||||||
|
- name: tests deps
|
||||||
|
run: |
|
||||||
|
cd micro-tests
|
||||||
|
go mod edit -replace="github.com/unistack-org/micro/v3=../"
|
||||||
|
go get -v -t -d ./...
|
||||||
|
- name: tests test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: cd micro-tests && go test -mod readonly -v ./...
|
||||||
|
lint:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
- name: lint
|
||||||
|
uses: golangci/golangci-lint-action@v1
|
||||||
|
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
|
||||||
22
.github/workflows/docker.yml
vendored
22
.github/workflows/docker.yml
vendored
@@ -1,22 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
tags:
|
|
||||||
- v2.*
|
|
||||||
- v3.*
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
name: Check out repository
|
|
||||||
- uses: elgohr/Publish-Docker-Github-Action@2.12
|
|
||||||
name: Build and Push Docker Image
|
|
||||||
with:
|
|
||||||
name: micro/go-micro
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
tag_names: true
|
|
||||||
76
.github/workflows/pr.yml
vendored
76
.github/workflows/pr.yml
vendored
@@ -1,28 +1,62 @@
|
|||||||
name: PR Sanity Check
|
name: prbuild
|
||||||
on: pull_request
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
jobs:
|
jobs:
|
||||||
|
test:
|
||||||
prtest:
|
name: test
|
||||||
name: PR sanity check
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- name: setup
|
||||||
- name: Set up Go 1.13
|
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v1
|
||||||
with:
|
with:
|
||||||
go-version: 1.13
|
go-version: 1.15
|
||||||
id: go
|
- name: cache
|
||||||
|
uses: actions/cache@v2
|
||||||
- name: Check out code into the Go module directory
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: ${{ runner.os }}-go-
|
||||||
|
- name: sdk checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
|
- name: sdk deps
|
||||||
- name: Get dependencies
|
run: go get -v -t -d ./...
|
||||||
run: |
|
- name: sdk test
|
||||||
go get -v -t -d ./...
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
id: tests
|
|
||||||
env:
|
env:
|
||||||
IN_TRAVIS_CI: yes
|
INTEGRATION_TESTS: yes
|
||||||
run: go test -v ./...
|
run: go test -mod readonly -v ./...
|
||||||
|
- name: tests checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
repository: unistack-org/micro-tests
|
||||||
|
ref: refs/heads/master
|
||||||
|
path: micro-tests
|
||||||
|
fetch-depth: 1
|
||||||
|
- name: tests deps
|
||||||
|
run: |
|
||||||
|
cd micro-tests
|
||||||
|
go mod edit -replace="github.com/unistack-org/micro/v3=../"
|
||||||
|
go get -v -t -d ./...
|
||||||
|
- name: tests test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: cd micro-tests && go test -mod readonly -v ./...
|
||||||
|
lint:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
- name: lint
|
||||||
|
uses: golangci/golangci-lint-action@v1
|
||||||
|
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
|
||||||
|
|||||||
41
.github/workflows/scripts/build-all-examples.sh
vendored
41
.github/workflows/scripts/build-all-examples.sh
vendored
@@ -1,41 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# set -x
|
|
||||||
|
|
||||||
function build_binary {
|
|
||||||
echo building $1
|
|
||||||
pushd $1
|
|
||||||
go build -o _main
|
|
||||||
local ret=$?
|
|
||||||
if [ $ret -gt 0 ]; then
|
|
||||||
failed=1
|
|
||||||
failed_arr+=($1)
|
|
||||||
fi
|
|
||||||
popd
|
|
||||||
}
|
|
||||||
|
|
||||||
function is_main {
|
|
||||||
grep "package main" -l -dskip $1/*.go > /dev/null 2>&1
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function check_dir {
|
|
||||||
is_main $1
|
|
||||||
local ret=$?
|
|
||||||
if [ $ret == 0 ]; then
|
|
||||||
build_binary $1 $2
|
|
||||||
fi
|
|
||||||
for filename in $1/*; do
|
|
||||||
if [ -d $filename ]; then
|
|
||||||
check_dir $filename $2
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
}
|
|
||||||
failed_arr=()
|
|
||||||
failed=0
|
|
||||||
go mod edit -replace github.com/micro/go-micro/v2=github.com/$2/v2@$1
|
|
||||||
check_dir . $1
|
|
||||||
if [ $failed -gt 0 ]; then
|
|
||||||
echo Some builds failed
|
|
||||||
printf '%s\n' "${failed_arr[@]}"
|
|
||||||
fi
|
|
||||||
exit $failed
|
|
||||||
19
.github/workflows/scripts/build-micro.sh
vendored
19
.github/workflows/scripts/build-micro.sh
vendored
@@ -1,19 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# set -x
|
|
||||||
|
|
||||||
failed=0
|
|
||||||
go mod edit -replace github.com/micro/go-micro/v2=github.com/$2/v2@$1
|
|
||||||
# basic test, build the binary
|
|
||||||
go install
|
|
||||||
failed=$?
|
|
||||||
if [ $failed -gt 0 ]; then
|
|
||||||
exit $failed
|
|
||||||
fi
|
|
||||||
# unit tests
|
|
||||||
IN_TRAVIS_CI=yes go test -v ./...
|
|
||||||
|
|
||||||
./scripts/test-docker.sh
|
|
||||||
# Generate keys for JWT tests
|
|
||||||
ssh-keygen -f /tmp/sshkey -m pkcs8 -q -N ""
|
|
||||||
ssh-keygen -f /tmp/sshkey -e -m pkcs8 > /tmp/sshkey.pub
|
|
||||||
go clean -testcache && IN_TRAVIS_CI=yes go test --tags=integration -v ./test
|
|
||||||
51
.github/workflows/tests.yml
vendored
51
.github/workflows/tests.yml
vendored
@@ -1,51 +0,0 @@
|
|||||||
name: Run tests
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
test:
|
|
||||||
name: Test repo
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- name: Set up Go 1.13
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.13
|
|
||||||
id: go
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Get dependencies
|
|
||||||
run: |
|
|
||||||
go get -v -t -d ./...
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
id: tests
|
|
||||||
env:
|
|
||||||
IN_TRAVIS_CI: yes
|
|
||||||
run: go test -v ./...
|
|
||||||
|
|
||||||
- name: Notify of test failure
|
|
||||||
if: failure()
|
|
||||||
uses: rtCamp/action-slack-notify@v2.0.0
|
|
||||||
env:
|
|
||||||
SLACK_CHANNEL: build
|
|
||||||
SLACK_COLOR: '#BF280A'
|
|
||||||
SLACK_ICON: https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png
|
|
||||||
SLACK_TITLE: Tests Failed
|
|
||||||
SLACK_USERNAME: GitHub Actions
|
|
||||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
- name: Notify of test success
|
|
||||||
if: success()
|
|
||||||
uses: rtCamp/action-slack-notify@v2.0.0
|
|
||||||
env:
|
|
||||||
SLACK_CHANNEL: build
|
|
||||||
SLACK_COLOR: '#1FAD2B'
|
|
||||||
SLACK_ICON: https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png
|
|
||||||
SLACK_TITLE: Tests Passed
|
|
||||||
SLACK_USERNAME: GitHub Actions
|
|
||||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
run:
|
run:
|
||||||
deadline: 10m
|
deadline: 5m
|
||||||
|
modules-download-mode: readonly
|
||||||
|
skip-dirs:
|
||||||
|
- util/mdns.new
|
||||||
|
skip-files:
|
||||||
|
- ".*\\.pb\\.go$"
|
||||||
|
- ".*\\.pb\\.micro\\.go$"
|
||||||
linters:
|
linters:
|
||||||
disable-all: false
|
disable-all: false
|
||||||
enable-all: false
|
enable-all: false
|
||||||
@@ -24,3 +30,11 @@ linters:
|
|||||||
- interfacer
|
- interfacer
|
||||||
- typecheck
|
- typecheck
|
||||||
- dupl
|
- dupl
|
||||||
|
output:
|
||||||
|
format: colored-line-number
|
||||||
|
# print lines of code with issue, default is true
|
||||||
|
print-issued-lines: true
|
||||||
|
# print linter name in the end of issue text, default is true
|
||||||
|
print-linter-name: true
|
||||||
|
# make issues output unique by line, default is true
|
||||||
|
uniq-by-line: true
|
||||||
|
|||||||
13
Dockerfile
13
Dockerfile
@@ -1,13 +0,0 @@
|
|||||||
FROM golang:1.13-alpine
|
|
||||||
|
|
||||||
RUN mkdir /user && \
|
|
||||||
echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \
|
|
||||||
echo 'nobody:x:65534:' > /user/group
|
|
||||||
|
|
||||||
ENV GO111MODULE=on
|
|
||||||
RUN apk --no-cache add make git gcc libtool musl-dev ca-certificates dumb-init && \
|
|
||||||
rm -rf /var/cache/apk/* /tmp/*
|
|
||||||
|
|
||||||
WORKDIR /
|
|
||||||
COPY ./go.mod ./go.sum ./
|
|
||||||
RUN go mod download && rm go.mod go.sum
|
|
||||||
3
LICENSE
3
LICENSE
@@ -176,7 +176,8 @@
|
|||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
Copyright 2015 Asim Aslam.
|
Copyright 2015-2020 Asim Aslam.
|
||||||
|
Copyright 2019-2020 Unistack LLC.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
30
README.md
30
README.md
@@ -1,16 +1,14 @@
|
|||||||
# Go Micro [](https://opensource.org/licenses/Apache-2.0) [](https://pkg.go.dev/github.com/micro/go-micro?tab=doc) [](https://travis-ci.org/micro/go-micro) [](https://goreportcard.com/report/github.com/micro/go-micro)
|
# Micro [](https://opensource.org/licenses/Apache-2.0) [](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [](https://goreportcard.com/report/github.com/unistack-org/micro) [](https://unistack-org.slack.com/messages/default)
|
||||||
|
|
||||||
Go Micro is a standard library for distributed systems development.
|
Micro is a standard library for microservices.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Go Micro provides the core requirements for distributed systems development including RPC and Event driven communication.
|
Micro provides the core requirements for distributed systems development including RPC and Event driven communication.
|
||||||
The **Micro** philosophy is sane defaults with a pluggable architecture. We provide defaults to get you started quickly
|
|
||||||
but everything can be easily swapped out.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
Go Micro abstracts away the details of distributed systems. Here are the main features.
|
Micro abstracts away the details of distributed systems. Here are the main features.
|
||||||
|
|
||||||
- **Authentication** - Auth is built in as a first class citizen. Authentication and authorization enable secure
|
- **Authentication** - Auth is built in as a first class citizen. Authentication and authorization enable secure
|
||||||
zero trust networking by providing every service an identity and certificates. This additionally includes rule
|
zero trust networking by providing every service an identity and certificates. This additionally includes rule
|
||||||
@@ -23,8 +21,7 @@ level config from any source such as env vars, file, etcd. You can merge the sou
|
|||||||
CockroachDB by default. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.
|
CockroachDB by default. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.
|
||||||
|
|
||||||
- **Service Discovery** - Automatic service registration and name resolution. Service discovery is at the core of micro service
|
- **Service Discovery** - Automatic service registration and name resolution. Service discovery is at the core of micro service
|
||||||
development. When service A needs to speak to service B it needs the location of that service. The default discovery mechanism is
|
development. When service A needs to speak to service B it needs the location of that service.
|
||||||
multicast DNS (mdns), a zeroconf system.
|
|
||||||
|
|
||||||
- **Load Balancing** - Client side load balancing built on service discovery. Once we have the addresses of any number of instances
|
- **Load Balancing** - Client side load balancing built on service discovery. Once we have the addresses of any number of instances
|
||||||
of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution
|
of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution
|
||||||
@@ -32,25 +29,24 @@ across the services and retry a different node if there's a problem.
|
|||||||
|
|
||||||
- **Message Encoding** - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type
|
- **Message Encoding** - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type
|
||||||
to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client
|
to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client
|
||||||
and server handle this by default. This includes protobuf and json by default.
|
and server handle this by default.
|
||||||
|
|
||||||
- **gRPC Transport** - gRPC based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.
|
- **Transport** - gRPC or http based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.
|
||||||
|
|
||||||
- **Async Messaging** - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures.
|
- **Async Messaging** - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures.
|
||||||
Event notifications are a core pattern in micro service development. The default messaging system is a HTTP event message broker.
|
Event notifications are a core pattern in micro service development.
|
||||||
|
|
||||||
- **Synchronization** - Distributed systems are often built in an eventually consistent manner. Support for distributed locking and
|
- **Synchronization** - Distributed systems are often built in an eventually consistent manner. Support for distributed locking and
|
||||||
leadership are built in as a Sync interface. When using an eventually consistent database or scheduling use the Sync interface.
|
leadership are built in as a Sync interface. When using an eventually consistent database or scheduling use the Sync interface.
|
||||||
|
|
||||||
- **Pluggable Interfaces** - Go Micro makes use of Go interfaces for each distributed system abstraction. Because of this these interfaces
|
- **Pluggable Interfaces** - Micro makes use of Go interfaces for each system abstraction. Because of this these interfaces
|
||||||
are pluggable and allows Go Micro to be runtime agnostic. You can plugin any underlying technology. Find plugins in
|
are pluggable and allows Micro to be runtime agnostic.
|
||||||
[github.com/micro/go-plugins](https://github.com/micro/go-plugins).
|
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
See [pkg.go.dev](https://pkg.go.dev/github.com/micro/go-micro?tab=doc) for usage.
|
To be created.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Go Micro is Apache 2.0 licensed.
|
Micro is Apache 2.0 licensed.
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
theme: jekyll-theme-architect
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
// Package agent provides an interface for building robots
|
|
||||||
package agent
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
// Package command is an interface for defining bot commands
|
|
||||||
package command
|
|
||||||
|
|
||||||
var (
|
|
||||||
// Commands keyed by golang/regexp patterns
|
|
||||||
// regexp.Match(key, input) is used to match
|
|
||||||
Commands = map[string]Command{}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Command is the interface for specific named
|
|
||||||
// commands executed via plugins or the bot.
|
|
||||||
type Command interface {
|
|
||||||
// Executes the command with args passed in
|
|
||||||
Exec(args ...string) ([]byte, error)
|
|
||||||
// Usage of the command
|
|
||||||
Usage() string
|
|
||||||
// Description of the command
|
|
||||||
Description() string
|
|
||||||
// Name of the command
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
type cmd struct {
|
|
||||||
name string
|
|
||||||
usage string
|
|
||||||
description string
|
|
||||||
exec func(args ...string) ([]byte, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cmd) Description() string {
|
|
||||||
return c.description
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cmd) Exec(args ...string) ([]byte, error) {
|
|
||||||
return c.exec(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cmd) Usage() string {
|
|
||||||
return c.usage
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cmd) String() string {
|
|
||||||
return c.name
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewCommand helps quickly create a new command
|
|
||||||
func NewCommand(name, usage, description string, exec func(args ...string) ([]byte, error)) Command {
|
|
||||||
return &cmd{
|
|
||||||
name: name,
|
|
||||||
usage: usage,
|
|
||||||
description: description,
|
|
||||||
exec: exec,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package command
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCommand(t *testing.T) {
|
|
||||||
c := &cmd{
|
|
||||||
name: "test",
|
|
||||||
usage: "test usage",
|
|
||||||
description: "test description",
|
|
||||||
exec: func(args ...string) ([]byte, error) {
|
|
||||||
return []byte("test"), nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.String() != c.name {
|
|
||||||
t.Fatalf("expected name %s got %s", c.name, c.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Usage() != c.usage {
|
|
||||||
t.Fatalf("expected usage %s got %s", c.usage, c.Usage())
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Description() != c.description {
|
|
||||||
t.Fatalf("expected description %s got %s", c.description, c.Description())
|
|
||||||
}
|
|
||||||
|
|
||||||
if r, err := c.Exec(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
} else if string(r) != "test" {
|
|
||||||
t.Fatalf("expected exec result test got %s", string(r))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewCommand(t *testing.T) {
|
|
||||||
c := &cmd{
|
|
||||||
name: "test",
|
|
||||||
usage: "test usage",
|
|
||||||
description: "test description",
|
|
||||||
exec: func(args ...string) ([]byte, error) {
|
|
||||||
return []byte("test"), nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
nc := NewCommand(c.name, c.usage, c.description, c.exec)
|
|
||||||
|
|
||||||
if nc.String() != c.name {
|
|
||||||
t.Fatalf("expected name %s got %s", c.name, nc.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
if nc.Usage() != c.usage {
|
|
||||||
t.Fatalf("expected usage %s got %s", c.usage, nc.Usage())
|
|
||||||
}
|
|
||||||
|
|
||||||
if nc.Description() != c.description {
|
|
||||||
t.Fatalf("expected description %s got %s", c.description, nc.Description())
|
|
||||||
}
|
|
||||||
|
|
||||||
if r, err := nc.Exec(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
} else if string(r) != "test" {
|
|
||||||
t.Fatalf("expected exec result test got %s", string(r))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
# Discord input for micro-bot
|
|
||||||
[Discord](https://discordapp.com) support for micro bot based on [discordgo](github.com/bwmarrin/discordgo).
|
|
||||||
|
|
||||||
This was originally written by Aleksandr Tihomirov (@zet4) and can be found at https://github.com/zet4/micro-misc/.
|
|
||||||
|
|
||||||
## Options
|
|
||||||
### discord_token
|
|
||||||
|
|
||||||
You have to supply an application token via `--discord_token`.
|
|
||||||
|
|
||||||
Head over to Discord's [developer introduction](https://discordapp.com/developers/docs/intro)
|
|
||||||
to learn how to create applications and how the API works.
|
|
||||||
|
|
||||||
### discord_prefix
|
|
||||||
|
|
||||||
Set a command prefix with `--discord_prefix`. The default prefix is `Micro `.
|
|
||||||
You can mention the bot or use the prefix to run a command.
|
|
||||||
|
|
||||||
### discord_whitelist
|
|
||||||
|
|
||||||
Pass a list of comma-separated user IDs with `--discord_whitelist`. Only allow
|
|
||||||
these users to use the bot.
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
package discord
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/bwmarrin/discordgo"
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type discordConn struct {
|
|
||||||
master *discordInput
|
|
||||||
exit chan struct{}
|
|
||||||
recv chan *discordgo.Message
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func newConn(master *discordInput) *discordConn {
|
|
||||||
conn := &discordConn{
|
|
||||||
master: master,
|
|
||||||
exit: make(chan struct{}),
|
|
||||||
recv: make(chan *discordgo.Message),
|
|
||||||
}
|
|
||||||
|
|
||||||
conn.master.session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
|
|
||||||
if m.Author.ID == master.botID {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
whitelisted := false
|
|
||||||
for _, ID := range conn.master.whitelist {
|
|
||||||
if m.Author.ID == ID {
|
|
||||||
whitelisted = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(master.whitelist) > 0 && !whitelisted {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var valid bool
|
|
||||||
m.Message.Content, valid = conn.master.prefixfn(m.Message.Content)
|
|
||||||
if !valid {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
conn.recv <- m.Message
|
|
||||||
})
|
|
||||||
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dc *discordConn) Recv(event *input.Event) error {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-dc.exit:
|
|
||||||
return errors.New("connection closed")
|
|
||||||
case msg := <-dc.recv:
|
|
||||||
|
|
||||||
event.From = msg.ChannelID + ":" + msg.Author.ID
|
|
||||||
event.To = dc.master.botID
|
|
||||||
event.Type = input.TextEvent
|
|
||||||
event.Data = []byte(msg.Content)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ChunkString(s string, chunkSize int) []string {
|
|
||||||
var chunks []string
|
|
||||||
runes := []rune(s)
|
|
||||||
|
|
||||||
if len(runes) == 0 {
|
|
||||||
return []string{s}
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < len(runes); i += chunkSize {
|
|
||||||
nn := i + chunkSize
|
|
||||||
if nn > len(runes) {
|
|
||||||
nn = len(runes)
|
|
||||||
}
|
|
||||||
chunks = append(chunks, string(runes[i:nn]))
|
|
||||||
}
|
|
||||||
return chunks
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dc *discordConn) Send(e *input.Event) error {
|
|
||||||
fields := strings.Split(e.To, ":")
|
|
||||||
for _, chunk := range ChunkString(string(e.Data), 2000) {
|
|
||||||
_, err := dc.master.session.ChannelMessageSend(fields[0], chunk)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error("[bot][loop][send]", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dc *discordConn) Close() error {
|
|
||||||
if err := dc.master.session.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-dc.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(dc.exit)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
package discord
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/bwmarrin/discordgo"
|
|
||||||
"github.com/micro/cli/v2"
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
input.Inputs["discord"] = newInput()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newInput() *discordInput {
|
|
||||||
return &discordInput{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type discordInput struct {
|
|
||||||
token string
|
|
||||||
whitelist []string
|
|
||||||
prefix string
|
|
||||||
prefixfn func(string) (string, bool)
|
|
||||||
botID string
|
|
||||||
|
|
||||||
session *discordgo.Session
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
running bool
|
|
||||||
exit chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) Flags() []cli.Flag {
|
|
||||||
return []cli.Flag{
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "discord_token",
|
|
||||||
EnvVars: []string{"MICRO_DISCORD_TOKEN"},
|
|
||||||
Usage: "Discord token (prefix with Bot if it's for bot account)",
|
|
||||||
},
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "discord_whitelist",
|
|
||||||
EnvVars: []string{"MICRO_DISCORD_WHITELIST"},
|
|
||||||
Usage: "Discord Whitelist (seperated by ,)",
|
|
||||||
},
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "discord_prefix",
|
|
||||||
Usage: "Discord Prefix",
|
|
||||||
EnvVars: []string{"MICRO_DISCORD_PREFIX"},
|
|
||||||
Value: "Micro ",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) Init(ctx *cli.Context) error {
|
|
||||||
token := ctx.String("discord_token")
|
|
||||||
whitelist := ctx.String("discord_whitelist")
|
|
||||||
prefix := ctx.String("discord_prefix")
|
|
||||||
|
|
||||||
if len(token) == 0 {
|
|
||||||
return errors.New("require token")
|
|
||||||
}
|
|
||||||
|
|
||||||
d.token = token
|
|
||||||
d.prefix = prefix
|
|
||||||
|
|
||||||
if len(whitelist) > 0 {
|
|
||||||
d.whitelist = strings.Split(whitelist, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) Start() error {
|
|
||||||
if len(d.token) == 0 {
|
|
||||||
return errors.New("missing discord configuration")
|
|
||||||
}
|
|
||||||
|
|
||||||
d.Lock()
|
|
||||||
defer d.Unlock()
|
|
||||||
|
|
||||||
if d.running {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
d.session, err = discordgo.New("Bot " + d.token)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := d.session.User("@me")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
d.botID = u.ID
|
|
||||||
d.prefixfn = CheckPrefixFactory(fmt.Sprintf("<@%s> ", d.botID), fmt.Sprintf("<@!%s> ", d.botID), d.prefix)
|
|
||||||
|
|
||||||
d.exit = make(chan struct{})
|
|
||||||
d.running = true
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) Stream() (input.Conn, error) {
|
|
||||||
d.Lock()
|
|
||||||
defer d.Unlock()
|
|
||||||
if !d.running {
|
|
||||||
return nil, errors.New("not running")
|
|
||||||
}
|
|
||||||
|
|
||||||
//Fire-n-forget close just in case...
|
|
||||||
d.session.Close()
|
|
||||||
|
|
||||||
conn := newConn(d)
|
|
||||||
if err := d.session.Open(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) Stop() error {
|
|
||||||
d.Lock()
|
|
||||||
defer d.Unlock()
|
|
||||||
|
|
||||||
if !d.running {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
close(d.exit)
|
|
||||||
d.running = false
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *discordInput) String() string {
|
|
||||||
return "discord"
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckPrefixFactory Creates a prefix checking function and stuff.
|
|
||||||
func CheckPrefixFactory(prefixes ...string) func(string) (string, bool) {
|
|
||||||
return func(content string) (string, bool) {
|
|
||||||
for _, prefix := range prefixes {
|
|
||||||
if strings.HasPrefix(content, prefix) {
|
|
||||||
return strings.TrimPrefix(content, prefix), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
// Package input is an interface for bot inputs
|
|
||||||
package input
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/cli/v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
type EventType string
|
|
||||||
|
|
||||||
const (
|
|
||||||
TextEvent EventType = "text"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// Inputs keyed by name
|
|
||||||
// Example slack or hipchat
|
|
||||||
Inputs = map[string]Input{}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Event is the unit sent and received
|
|
||||||
type Event struct {
|
|
||||||
Type EventType
|
|
||||||
From string
|
|
||||||
To string
|
|
||||||
Data []byte
|
|
||||||
Meta map[string]interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Input is an interface for sources which
|
|
||||||
// provide a way to communicate with the bot.
|
|
||||||
// Slack, HipChat, XMPP, etc.
|
|
||||||
type Input interface {
|
|
||||||
// Provide cli flags
|
|
||||||
Flags() []cli.Flag
|
|
||||||
// Initialise input using cli context
|
|
||||||
Init(*cli.Context) error
|
|
||||||
// Stream events from the input
|
|
||||||
Stream() (Conn, error)
|
|
||||||
// Start the input
|
|
||||||
Start() error
|
|
||||||
// Stop the input
|
|
||||||
Stop() error
|
|
||||||
// name of the input
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conn interface provides a way to
|
|
||||||
// send and receive events. Send and
|
|
||||||
// Recv both block until succeeding
|
|
||||||
// or failing.
|
|
||||||
type Conn interface {
|
|
||||||
Close() error
|
|
||||||
Recv(*Event) error
|
|
||||||
Send(*Event) error
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package slack
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
"github.com/nlopes/slack"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Satisfies the input.Conn interface
|
|
||||||
type slackConn struct {
|
|
||||||
auth *slack.AuthTestResponse
|
|
||||||
rtm *slack.RTM
|
|
||||||
exit chan bool
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
names map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *slackConn) run() {
|
|
||||||
// func retrieves user names and maps to IDs
|
|
||||||
setNames := func() {
|
|
||||||
names := make(map[string]string)
|
|
||||||
users, err := s.rtm.Client.GetUsers()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, user := range users {
|
|
||||||
names[user.ID] = user.Name
|
|
||||||
}
|
|
||||||
|
|
||||||
s.Lock()
|
|
||||||
s.names = names
|
|
||||||
s.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
setNames()
|
|
||||||
|
|
||||||
t := time.NewTicker(time.Minute)
|
|
||||||
defer t.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-s.exit:
|
|
||||||
return
|
|
||||||
case <-t.C:
|
|
||||||
setNames()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *slackConn) getName(id string) string {
|
|
||||||
s.Lock()
|
|
||||||
name := s.names[id]
|
|
||||||
s.Unlock()
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *slackConn) Close() error {
|
|
||||||
select {
|
|
||||||
case <-s.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(s.exit)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *slackConn) Recv(event *input.Event) error {
|
|
||||||
if event == nil {
|
|
||||||
return errors.New("event cannot be nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-s.exit:
|
|
||||||
return errors.New("connection closed")
|
|
||||||
case e := <-s.rtm.IncomingEvents:
|
|
||||||
switch ev := e.Data.(type) {
|
|
||||||
case *slack.MessageEvent:
|
|
||||||
// only accept type message
|
|
||||||
if ev.Type != "message" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// only accept DMs or messages to me
|
|
||||||
switch {
|
|
||||||
case strings.HasPrefix(ev.Channel, "D"):
|
|
||||||
case strings.HasPrefix(ev.Text, s.auth.User):
|
|
||||||
case strings.HasPrefix(ev.Text, fmt.Sprintf("<@%s>", s.auth.UserID)):
|
|
||||||
default:
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strip username from text
|
|
||||||
switch {
|
|
||||||
case strings.HasPrefix(ev.Text, s.auth.User):
|
|
||||||
args := strings.Split(ev.Text, " ")[1:]
|
|
||||||
ev.Text = strings.Join(args, " ")
|
|
||||||
event.To = s.auth.User
|
|
||||||
case strings.HasPrefix(ev.Text, fmt.Sprintf("<@%s>", s.auth.UserID)):
|
|
||||||
args := strings.Split(ev.Text, " ")[1:]
|
|
||||||
ev.Text = strings.Join(args, " ")
|
|
||||||
event.To = s.auth.UserID
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Meta == nil {
|
|
||||||
event.Meta = make(map[string]interface{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// fill in the blanks
|
|
||||||
event.From = ev.Channel + ":" + ev.User
|
|
||||||
event.Type = input.TextEvent
|
|
||||||
event.Data = []byte(ev.Text)
|
|
||||||
event.Meta["reply"] = ev
|
|
||||||
return nil
|
|
||||||
case *slack.InvalidAuthEvent:
|
|
||||||
return errors.New("invalid credentials")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *slackConn) Send(event *input.Event) error {
|
|
||||||
var channel, message, name string
|
|
||||||
|
|
||||||
if len(event.To) == 0 {
|
|
||||||
return errors.New("require Event.To")
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(event.To, ":")
|
|
||||||
|
|
||||||
if len(parts) == 2 {
|
|
||||||
channel = parts[0]
|
|
||||||
name = s.getName(parts[1])
|
|
||||||
// try using reply meta
|
|
||||||
} else if ev, ok := event.Meta["reply"]; ok {
|
|
||||||
channel = ev.(*slack.MessageEvent).Channel
|
|
||||||
name = s.getName(ev.(*slack.MessageEvent).User)
|
|
||||||
}
|
|
||||||
|
|
||||||
// don't know where to send the message
|
|
||||||
if len(channel) == 0 {
|
|
||||||
return errors.New("could not determine who message is to")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(name) == 0 || strings.HasPrefix(channel, "D") {
|
|
||||||
message = string(event.Data)
|
|
||||||
} else {
|
|
||||||
message = fmt.Sprintf("@%s: %s", name, string(event.Data))
|
|
||||||
}
|
|
||||||
|
|
||||||
s.rtm.SendMessage(s.rtm.NewOutgoingMessage(message, channel))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
package slack
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/cli/v2"
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
"github.com/nlopes/slack"
|
|
||||||
)
|
|
||||||
|
|
||||||
type slackInput struct {
|
|
||||||
debug bool
|
|
||||||
token string
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
running bool
|
|
||||||
exit chan bool
|
|
||||||
|
|
||||||
api *slack.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
input.Inputs["slack"] = NewInput()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) Flags() []cli.Flag {
|
|
||||||
return []cli.Flag{
|
|
||||||
&cli.BoolFlag{
|
|
||||||
Name: "slack_debug",
|
|
||||||
Usage: "Slack debug output",
|
|
||||||
EnvVars: []string{"MICRO_SLACK_DEBUG"},
|
|
||||||
},
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "slack_token",
|
|
||||||
Usage: "Slack token",
|
|
||||||
EnvVars: []string{"MICRO_SLACK_TOKEN"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) Init(ctx *cli.Context) error {
|
|
||||||
debug := ctx.Bool("slack_debug")
|
|
||||||
token := ctx.String("slack_token")
|
|
||||||
|
|
||||||
if len(token) == 0 {
|
|
||||||
return errors.New("missing slack token")
|
|
||||||
}
|
|
||||||
|
|
||||||
p.debug = debug
|
|
||||||
p.token = token
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) Stream() (input.Conn, error) {
|
|
||||||
p.Lock()
|
|
||||||
defer p.Unlock()
|
|
||||||
|
|
||||||
if !p.running {
|
|
||||||
return nil, errors.New("not running")
|
|
||||||
}
|
|
||||||
|
|
||||||
// test auth
|
|
||||||
auth, err := p.api.AuthTest()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
rtm := p.api.NewRTM()
|
|
||||||
exit := make(chan bool)
|
|
||||||
|
|
||||||
go rtm.ManageConnection()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-p.exit:
|
|
||||||
select {
|
|
||||||
case <-exit:
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
close(exit)
|
|
||||||
}
|
|
||||||
case <-exit:
|
|
||||||
}
|
|
||||||
|
|
||||||
rtm.Disconnect()
|
|
||||||
}()
|
|
||||||
|
|
||||||
conn := &slackConn{
|
|
||||||
auth: auth,
|
|
||||||
rtm: rtm,
|
|
||||||
exit: exit,
|
|
||||||
names: make(map[string]string),
|
|
||||||
}
|
|
||||||
|
|
||||||
go conn.run()
|
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) Start() error {
|
|
||||||
if len(p.token) == 0 {
|
|
||||||
return errors.New("missing slack token")
|
|
||||||
}
|
|
||||||
|
|
||||||
p.Lock()
|
|
||||||
defer p.Unlock()
|
|
||||||
|
|
||||||
if p.running {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
api := slack.New(p.token, slack.OptionDebug(p.debug))
|
|
||||||
|
|
||||||
// test auth
|
|
||||||
_, err := api.AuthTest()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
p.api = api
|
|
||||||
p.exit = make(chan bool)
|
|
||||||
p.running = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) Stop() error {
|
|
||||||
p.Lock()
|
|
||||||
defer p.Unlock()
|
|
||||||
|
|
||||||
if !p.running {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
close(p.exit)
|
|
||||||
p.running = false
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *slackInput) String() string {
|
|
||||||
return "slack"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInput() input.Input {
|
|
||||||
return &slackInput{}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Telegram Messenger input for micro bot
|
|
||||||
[Telegram](https://telegram.org) support for micro bot based on [telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api).
|
|
||||||
|
|
||||||
## Options
|
|
||||||
### --telegram_token (required)
|
|
||||||
|
|
||||||
Sets bot's token for interacting with API.
|
|
||||||
|
|
||||||
Head over to Telegram's [API documentation](https://core.telegram.org/bots/api)
|
|
||||||
to learn how to create bots and how the API works.
|
|
||||||
|
|
||||||
### --telegram_debug
|
|
||||||
|
|
||||||
Sets the debug flag to make the bot's output verbose.
|
|
||||||
|
|
||||||
### --telegram_whitelist
|
|
||||||
|
|
||||||
Sets a list of comma-separated nicknames (without @ symbol in the beginning) for interacting with bot. Only these users can use the bot.
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
package telegram
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/forestgiant/sliceutil"
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
tgbotapi "gopkg.in/telegram-bot-api.v4"
|
|
||||||
)
|
|
||||||
|
|
||||||
type telegramConn struct {
|
|
||||||
input *telegramInput
|
|
||||||
|
|
||||||
recv <-chan tgbotapi.Update
|
|
||||||
exit chan bool
|
|
||||||
|
|
||||||
syncCond *sync.Cond
|
|
||||||
mutex sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func newConn(input *telegramInput) (*telegramConn, error) {
|
|
||||||
conn := &telegramConn{
|
|
||||||
input: input,
|
|
||||||
}
|
|
||||||
|
|
||||||
conn.syncCond = sync.NewCond(&conn.mutex)
|
|
||||||
|
|
||||||
go conn.run()
|
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tc *telegramConn) run() {
|
|
||||||
u := tgbotapi.NewUpdate(0)
|
|
||||||
u.Timeout = 60
|
|
||||||
updates, err := tc.input.api.GetUpdatesChan(u)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tc.recv = updates
|
|
||||||
tc.syncCond.Signal()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-tc.exit:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tc *telegramConn) Close() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tc *telegramConn) Recv(event *input.Event) error {
|
|
||||||
if event == nil {
|
|
||||||
return errors.New("event cannot be nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
if tc.recv == nil {
|
|
||||||
tc.mutex.Lock()
|
|
||||||
tc.syncCond.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
update := <-tc.recv
|
|
||||||
|
|
||||||
if update.Message == nil || (len(tc.input.whitelist) > 0 && !sliceutil.Contains(tc.input.whitelist, update.Message.From.UserName)) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Meta == nil {
|
|
||||||
event.Meta = make(map[string]interface{})
|
|
||||||
}
|
|
||||||
|
|
||||||
event.Type = input.TextEvent
|
|
||||||
event.From = update.Message.From.UserName
|
|
||||||
event.To = tc.input.api.Self.UserName
|
|
||||||
event.Data = []byte(update.Message.Text)
|
|
||||||
event.Meta["chatId"] = update.Message.Chat.ID
|
|
||||||
event.Meta["chatType"] = update.Message.Chat.Type
|
|
||||||
event.Meta["messageId"] = update.Message.MessageID
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tc *telegramConn) Send(event *input.Event) error {
|
|
||||||
messageText := strings.TrimSpace(string(event.Data))
|
|
||||||
|
|
||||||
chatId := event.Meta["chatId"].(int64)
|
|
||||||
chatType := ChatType(event.Meta["chatType"].(string))
|
|
||||||
|
|
||||||
msgConfig := tgbotapi.NewMessage(chatId, messageText)
|
|
||||||
msgConfig.ParseMode = tgbotapi.ModeHTML
|
|
||||||
|
|
||||||
if sliceutil.Contains([]ChatType{Group, Supergroup}, chatType) {
|
|
||||||
msgConfig.ReplyToMessageID = event.Meta["messageId"].(int)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := tc.input.api.Send(msgConfig)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
// probably it could be because of nested HTML tags -- telegram doesn't allow nested tags
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error("[telegram][Send] error:", err)
|
|
||||||
}
|
|
||||||
msgConfig.Text = "This bot couldn't send the response (Internal error)"
|
|
||||||
tc.input.api.Send(msgConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
package telegram
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/cli/v2"
|
|
||||||
"github.com/micro/go-micro/v3/agent/input"
|
|
||||||
tgbotapi "gopkg.in/telegram-bot-api.v4"
|
|
||||||
)
|
|
||||||
|
|
||||||
type telegramInput struct {
|
|
||||||
sync.Mutex
|
|
||||||
|
|
||||||
debug bool
|
|
||||||
token string
|
|
||||||
whitelist []string
|
|
||||||
|
|
||||||
api *tgbotapi.BotAPI
|
|
||||||
}
|
|
||||||
|
|
||||||
type ChatType string
|
|
||||||
|
|
||||||
const (
|
|
||||||
Private ChatType = "private"
|
|
||||||
Group ChatType = "group"
|
|
||||||
Supergroup ChatType = "supergroup"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
input.Inputs["telegram"] = &telegramInput{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *telegramInput) Flags() []cli.Flag {
|
|
||||||
return []cli.Flag{
|
|
||||||
&cli.BoolFlag{
|
|
||||||
Name: "telegram_debug",
|
|
||||||
EnvVars: []string{"MICRO_TELEGRAM_DEBUG"},
|
|
||||||
Usage: "Telegram debug output",
|
|
||||||
},
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "telegram_token",
|
|
||||||
EnvVars: []string{"MICRO_TELEGRAM_TOKEN"},
|
|
||||||
Usage: "Telegram token",
|
|
||||||
},
|
|
||||||
&cli.StringFlag{
|
|
||||||
Name: "telegram_whitelist",
|
|
||||||
EnvVars: []string{"MICRO_TELEGRAM_WHITELIST"},
|
|
||||||
Usage: "Telegram bot's users (comma-separated values)",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *telegramInput) Init(ctx *cli.Context) error {
|
|
||||||
ti.debug = ctx.Bool("telegram_debug")
|
|
||||||
ti.token = ctx.String("telegram_token")
|
|
||||||
|
|
||||||
whitelist := ctx.String("telegram_whitelist")
|
|
||||||
|
|
||||||
if whitelist != "" {
|
|
||||||
ti.whitelist = strings.Split(whitelist, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(ti.token) == 0 {
|
|
||||||
return errors.New("missing telegram token")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *telegramInput) Stream() (input.Conn, error) {
|
|
||||||
ti.Lock()
|
|
||||||
defer ti.Unlock()
|
|
||||||
|
|
||||||
return newConn(ti)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *telegramInput) Start() error {
|
|
||||||
ti.Lock()
|
|
||||||
defer ti.Unlock()
|
|
||||||
|
|
||||||
api, err := tgbotapi.NewBotAPI(ti.token)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
ti.api = api
|
|
||||||
|
|
||||||
api.Debug = ti.debug
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *telegramInput) Stop() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *telegramInput) String() string {
|
|
||||||
return "telegram"
|
|
||||||
}
|
|
||||||
@@ -1,333 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// source: agent/proto/bot.proto
|
|
||||||
|
|
||||||
package go_micro_bot
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
grpc "google.golang.org/grpc"
|
|
||||||
codes "google.golang.org/grpc/codes"
|
|
||||||
status "google.golang.org/grpc/status"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
type HelpRequest struct {
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *HelpRequest) Reset() { *m = HelpRequest{} }
|
|
||||||
func (m *HelpRequest) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*HelpRequest) ProtoMessage() {}
|
|
||||||
func (*HelpRequest) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_79b974b8c77805fa, []int{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *HelpRequest) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_HelpRequest.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *HelpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_HelpRequest.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *HelpRequest) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_HelpRequest.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *HelpRequest) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_HelpRequest.Size(m)
|
|
||||||
}
|
|
||||||
func (m *HelpRequest) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_HelpRequest.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_HelpRequest proto.InternalMessageInfo
|
|
||||||
|
|
||||||
type HelpResponse struct {
|
|
||||||
Usage string `protobuf:"bytes,1,opt,name=usage,proto3" json:"usage,omitempty"`
|
|
||||||
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *HelpResponse) Reset() { *m = HelpResponse{} }
|
|
||||||
func (m *HelpResponse) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*HelpResponse) ProtoMessage() {}
|
|
||||||
func (*HelpResponse) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_79b974b8c77805fa, []int{1}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *HelpResponse) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_HelpResponse.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *HelpResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_HelpResponse.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *HelpResponse) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_HelpResponse.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *HelpResponse) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_HelpResponse.Size(m)
|
|
||||||
}
|
|
||||||
func (m *HelpResponse) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_HelpResponse.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_HelpResponse proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *HelpResponse) GetUsage() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Usage
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *HelpResponse) GetDescription() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Description
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
type ExecRequest struct {
|
|
||||||
Args []string `protobuf:"bytes,1,rep,name=args,proto3" json:"args,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExecRequest) Reset() { *m = ExecRequest{} }
|
|
||||||
func (m *ExecRequest) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*ExecRequest) ProtoMessage() {}
|
|
||||||
func (*ExecRequest) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_79b974b8c77805fa, []int{2}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExecRequest) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_ExecRequest.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *ExecRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_ExecRequest.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *ExecRequest) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_ExecRequest.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *ExecRequest) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_ExecRequest.Size(m)
|
|
||||||
}
|
|
||||||
func (m *ExecRequest) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_ExecRequest.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_ExecRequest proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *ExecRequest) GetArgs() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Args
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ExecResponse struct {
|
|
||||||
Result []byte `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"`
|
|
||||||
Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExecResponse) Reset() { *m = ExecResponse{} }
|
|
||||||
func (m *ExecResponse) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*ExecResponse) ProtoMessage() {}
|
|
||||||
func (*ExecResponse) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_79b974b8c77805fa, []int{3}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExecResponse) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_ExecResponse.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *ExecResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_ExecResponse.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *ExecResponse) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_ExecResponse.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *ExecResponse) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_ExecResponse.Size(m)
|
|
||||||
}
|
|
||||||
func (m *ExecResponse) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_ExecResponse.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_ExecResponse proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *ExecResponse) GetResult() []byte {
|
|
||||||
if m != nil {
|
|
||||||
return m.Result
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExecResponse) GetError() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Error
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
proto.RegisterType((*HelpRequest)(nil), "go.micro.bot.HelpRequest")
|
|
||||||
proto.RegisterType((*HelpResponse)(nil), "go.micro.bot.HelpResponse")
|
|
||||||
proto.RegisterType((*ExecRequest)(nil), "go.micro.bot.ExecRequest")
|
|
||||||
proto.RegisterType((*ExecResponse)(nil), "go.micro.bot.ExecResponse")
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() { proto.RegisterFile("agent/proto/bot.proto", fileDescriptor_79b974b8c77805fa) }
|
|
||||||
|
|
||||||
var fileDescriptor_79b974b8c77805fa = []byte{
|
|
||||||
// 234 bytes of a gzipped FileDescriptorProto
|
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x3f, 0x4f, 0xc3, 0x30,
|
|
||||||
0x10, 0xc5, 0x1b, 0x28, 0x45, 0xbd, 0x84, 0xc5, 0x02, 0x14, 0x3a, 0x05, 0x4f, 0x9d, 0x5c, 0x09,
|
|
||||||
0x56, 0x24, 0x06, 0x04, 0x62, 0xce, 0x37, 0x48, 0xd2, 0x53, 0x14, 0xa9, 0xf1, 0x99, 0xb3, 0x23,
|
|
||||||
0xf1, 0x1d, 0xf8, 0xd2, 0xc8, 0x7f, 0x06, 0xab, 0xea, 0x76, 0xcf, 0x67, 0xbd, 0xf7, 0x7b, 0x07,
|
|
||||||
0x0f, 0xdd, 0x88, 0xda, 0x1d, 0x0c, 0x93, 0xa3, 0x43, 0x4f, 0x4e, 0x85, 0x49, 0x54, 0x23, 0xa9,
|
|
||||||
0x79, 0x1a, 0x98, 0x54, 0x4f, 0x4e, 0xde, 0x41, 0xf9, 0x8d, 0x27, 0xd3, 0xe2, 0xcf, 0x82, 0xd6,
|
|
||||||
0xc9, 0x2f, 0xa8, 0xa2, 0xb4, 0x86, 0xb4, 0x45, 0x71, 0x0f, 0x37, 0x8b, 0xed, 0x46, 0xac, 0x8b,
|
|
||||||
0xa6, 0xd8, 0x6f, 0xdb, 0x28, 0x44, 0x03, 0xe5, 0x11, 0xed, 0xc0, 0x93, 0x71, 0x13, 0xe9, 0xfa,
|
|
||||||
0x2a, 0xec, 0xf2, 0x27, 0xf9, 0x0c, 0xe5, 0xe7, 0x2f, 0x0e, 0xc9, 0x56, 0x08, 0x58, 0x77, 0x3c,
|
|
||||||
0xda, 0xba, 0x68, 0xae, 0xf7, 0xdb, 0x36, 0xcc, 0xf2, 0x0d, 0xaa, 0xf8, 0x25, 0x45, 0x3d, 0xc2,
|
|
||||||
0x86, 0xd1, 0x2e, 0x27, 0x17, 0xb2, 0xaa, 0x36, 0x29, 0x8f, 0x80, 0xcc, 0xc4, 0x29, 0x26, 0x8a,
|
|
||||||
0x97, 0xbf, 0x02, 0x6e, 0x3f, 0x68, 0x9e, 0x3b, 0x7d, 0x14, 0xef, 0xb0, 0xf6, 0xd0, 0xe2, 0x49,
|
|
||||||
0xe5, 0xd5, 0x54, 0xd6, 0x6b, 0xb7, 0xbb, 0xb4, 0x8a, 0xc1, 0x72, 0xe5, 0x0d, 0x3c, 0xca, 0xb9,
|
|
||||||
0x41, 0xd6, 0xe0, 0xdc, 0x20, 0x27, 0x97, 0xab, 0x7e, 0x13, 0x4e, 0xfb, 0xfa, 0x1f, 0x00, 0x00,
|
|
||||||
0xff, 0xff, 0xe8, 0x08, 0x5e, 0xad, 0x73, 0x01, 0x00, 0x00,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ context.Context
|
|
||||||
var _ grpc.ClientConn
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the grpc package it is being compiled against.
|
|
||||||
const _ = grpc.SupportPackageIsVersion4
|
|
||||||
|
|
||||||
// CommandClient is the client API for Command service.
|
|
||||||
//
|
|
||||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
|
|
||||||
type CommandClient interface {
|
|
||||||
Help(ctx context.Context, in *HelpRequest, opts ...grpc.CallOption) (*HelpResponse, error)
|
|
||||||
Exec(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (*ExecResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type commandClient struct {
|
|
||||||
cc *grpc.ClientConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCommandClient(cc *grpc.ClientConn) CommandClient {
|
|
||||||
return &commandClient{cc}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *commandClient) Help(ctx context.Context, in *HelpRequest, opts ...grpc.CallOption) (*HelpResponse, error) {
|
|
||||||
out := new(HelpResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.bot.Command/Help", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *commandClient) Exec(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (*ExecResponse, error) {
|
|
||||||
out := new(ExecResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.bot.Command/Exec", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CommandServer is the server API for Command service.
|
|
||||||
type CommandServer interface {
|
|
||||||
Help(context.Context, *HelpRequest) (*HelpResponse, error)
|
|
||||||
Exec(context.Context, *ExecRequest) (*ExecResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnimplementedCommandServer can be embedded to have forward compatible implementations.
|
|
||||||
type UnimplementedCommandServer struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*UnimplementedCommandServer) Help(ctx context.Context, req *HelpRequest) (*HelpResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Help not implemented")
|
|
||||||
}
|
|
||||||
func (*UnimplementedCommandServer) Exec(ctx context.Context, req *ExecRequest) (*ExecResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Exec not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterCommandServer(s *grpc.Server, srv CommandServer) {
|
|
||||||
s.RegisterService(&_Command_serviceDesc, srv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Command_Help_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(HelpRequest)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(CommandServer).Help(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.bot.Command/Help",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(CommandServer).Help(ctx, req.(*HelpRequest))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Command_Exec_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(ExecRequest)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(CommandServer).Exec(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.bot.Command/Exec",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(CommandServer).Exec(ctx, req.(*ExecRequest))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
var _Command_serviceDesc = grpc.ServiceDesc{
|
|
||||||
ServiceName: "go.micro.bot.Command",
|
|
||||||
HandlerType: (*CommandServer)(nil),
|
|
||||||
Methods: []grpc.MethodDesc{
|
|
||||||
{
|
|
||||||
MethodName: "Help",
|
|
||||||
Handler: _Command_Help_Handler,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
MethodName: "Exec",
|
|
||||||
Handler: _Command_Exec_Handler,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Streams: []grpc.StreamDesc{},
|
|
||||||
Metadata: "agent/proto/bot.proto",
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
|
||||||
// source: agent/proto/bot.proto
|
|
||||||
|
|
||||||
package go_micro_bot
|
|
||||||
|
|
||||||
import (
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
api "github.com/micro/go-micro/v3/api"
|
|
||||||
client "github.com/micro/go-micro/v3/client"
|
|
||||||
server "github.com/micro/go-micro/v3/server"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ api.Endpoint
|
|
||||||
var _ context.Context
|
|
||||||
var _ client.Option
|
|
||||||
var _ server.Option
|
|
||||||
|
|
||||||
// Api Endpoints for Command service
|
|
||||||
|
|
||||||
func NewCommandEndpoints() []*api.Endpoint {
|
|
||||||
return []*api.Endpoint{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client API for Command service
|
|
||||||
|
|
||||||
type CommandService interface {
|
|
||||||
Help(ctx context.Context, in *HelpRequest, opts ...client.CallOption) (*HelpResponse, error)
|
|
||||||
Exec(ctx context.Context, in *ExecRequest, opts ...client.CallOption) (*ExecResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type commandService struct {
|
|
||||||
c client.Client
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCommandService(name string, c client.Client) CommandService {
|
|
||||||
return &commandService{
|
|
||||||
c: c,
|
|
||||||
name: name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *commandService) Help(ctx context.Context, in *HelpRequest, opts ...client.CallOption) (*HelpResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Command.Help", in)
|
|
||||||
out := new(HelpResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *commandService) Exec(ctx context.Context, in *ExecRequest, opts ...client.CallOption) (*ExecResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Command.Exec", in)
|
|
||||||
out := new(ExecResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server API for Command service
|
|
||||||
|
|
||||||
type CommandHandler interface {
|
|
||||||
Help(context.Context, *HelpRequest, *HelpResponse) error
|
|
||||||
Exec(context.Context, *ExecRequest, *ExecResponse) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterCommandHandler(s server.Server, hdlr CommandHandler, opts ...server.HandlerOption) error {
|
|
||||||
type command interface {
|
|
||||||
Help(ctx context.Context, in *HelpRequest, out *HelpResponse) error
|
|
||||||
Exec(ctx context.Context, in *ExecRequest, out *ExecResponse) error
|
|
||||||
}
|
|
||||||
type Command struct {
|
|
||||||
command
|
|
||||||
}
|
|
||||||
h := &commandHandler{hdlr}
|
|
||||||
return s.Handle(s.NewHandler(&Command{h}, opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
type commandHandler struct {
|
|
||||||
CommandHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *commandHandler) Help(ctx context.Context, in *HelpRequest, out *HelpResponse) error {
|
|
||||||
return h.CommandHandler.Help(ctx, in, out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *commandHandler) Exec(ctx context.Context, in *ExecRequest, out *ExecResponse) error {
|
|
||||||
return h.CommandHandler.Exec(ctx, in, out)
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package go.micro.bot;
|
|
||||||
|
|
||||||
service Command {
|
|
||||||
rpc Help(HelpRequest) returns (HelpResponse) {};
|
|
||||||
rpc Exec(ExecRequest) returns (ExecResponse) {};
|
|
||||||
}
|
|
||||||
|
|
||||||
message HelpRequest {
|
|
||||||
}
|
|
||||||
|
|
||||||
message HelpResponse {
|
|
||||||
string usage = 1;
|
|
||||||
string description = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ExecRequest {
|
|
||||||
repeated string args = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ExecResponse {
|
|
||||||
bytes result = 1;
|
|
||||||
string error = 2;
|
|
||||||
}
|
|
||||||
@@ -5,8 +5,8 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
"github.com/micro/go-micro/v3/server"
|
"github.com/unistack-org/micro/v3/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Api interface {
|
type Api interface {
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ package api
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
goapi "github.com/micro/go-micro/v3/api"
|
goapi "github.com/unistack-org/micro/v3/api"
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
"github.com/micro/go-micro/v3/api/handler/util"
|
api "github.com/unistack-org/micro/v3/api/proto"
|
||||||
api "github.com/micro/go-micro/v3/api/proto"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"github.com/micro/go-micro/v3/client"
|
"github.com/unistack-org/micro/v3/errors"
|
||||||
"github.com/micro/go-micro/v3/errors"
|
"github.com/unistack-org/micro/v3/util/ctx"
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
"github.com/unistack-org/micro/v3/util/router"
|
||||||
)
|
)
|
||||||
|
|
||||||
type apiHandler struct {
|
type apiHandler struct {
|
||||||
@@ -72,7 +72,7 @@ func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
// create the context from headers
|
// create the context from headers
|
||||||
cx := ctx.FromRequest(r)
|
cx := ctx.FromRequest(r)
|
||||||
|
|
||||||
if err := c.Call(cx, req, rsp, client.WithRouter(util.Router(service.Services))); err != nil {
|
if err := c.Call(cx, req, rsp, client.WithRouter(router.New(service.Services))); err != nil {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
ce := errors.Parse(err.Error())
|
ce := errors.Parse(err.Error())
|
||||||
switch ce.Code {
|
switch ce.Code {
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
api "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
"github.com/oxtoacart/bpool"
|
"github.com/oxtoacart/bpool"
|
||||||
|
api "github.com/unistack-org/micro/v3/api/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
proto "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
|
||||||
"github.com/oxtoacart/bpool"
|
"github.com/oxtoacart/bpool"
|
||||||
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
|
proto "github.com/unistack-org/micro/v3/api/proto"
|
||||||
|
"github.com/unistack-org/micro/v3/util/ctx"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ import (
|
|||||||
"net/http/httputil"
|
"net/http/httputil"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
"github.com/unistack-org/micro/v3/api"
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -65,16 +65,17 @@ func (h *httpHandler) getService(r *http.Request) (string, error) {
|
|||||||
return "", errors.New("no route found")
|
return "", errors.New("no route found")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(service.Services) == 0 {
|
||||||
|
return "", errors.New("no route found")
|
||||||
|
}
|
||||||
|
|
||||||
// get the nodes for this service
|
// get the nodes for this service
|
||||||
var nodes []*registry.Node
|
nodes := make([]*registry.Node, 0, len(service.Services))
|
||||||
for _, srv := range service.Services {
|
for _, srv := range service.Services {
|
||||||
nodes = append(nodes, srv.Nodes...)
|
nodes = append(nodes, srv.Nodes...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// select a random node
|
// select a random node
|
||||||
if len(nodes) == 0 {
|
|
||||||
return "", errors.New("no route found")
|
|
||||||
}
|
|
||||||
node := nodes[rand.Int()%len(nodes)]
|
node := nodes[rand.Int()%len(nodes)]
|
||||||
|
|
||||||
return fmt.Sprintf("http://%s", node.Address), nil
|
return fmt.Sprintf("http://%s", node.Address), nil
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// +build ignore
|
||||||
|
|
||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,13 +8,13 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
"github.com/unistack-org/micro/v3/api/router"
|
||||||
regRouter "github.com/micro/go-micro/v3/api/router/registry"
|
regRouter "github.com/unistack-org/micro/v3/api/router/registry"
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
"github.com/micro/go-micro/v3/registry/memory"
|
"github.com/unistack-org/micro/v3/registry/memory"
|
||||||
)
|
)
|
||||||
|
|
||||||
func testHttp(t *testing.T, path, service, ns string) {
|
func testHttp(t *testing.T, path, service, ns string) {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
"github.com/unistack-org/micro/v3/api/router"
|
||||||
"github.com/micro/go-micro/v3/client"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
"github.com/micro/go-micro/v3/client/grpc"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -26,10 +25,6 @@ func NewOptions(opts ...Option) Options {
|
|||||||
o(&options)
|
o(&options)
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.Client == nil {
|
|
||||||
WithClient(grpc.NewClient())(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set namespace if blank
|
// set namespace if blank
|
||||||
if len(options.Namespace) == 0 {
|
if len(options.Namespace) == 0 {
|
||||||
WithNamespace("go.micro.api")(&options)
|
WithNamespace("go.micro.api")(&options)
|
||||||
|
|||||||
@@ -9,20 +9,20 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
jsonpatch "github.com/evanphx/json-patch/v5"
|
jsonpatch "github.com/evanphx/json-patch/v5"
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler/util"
|
|
||||||
"github.com/micro/go-micro/v3/api/internal/proto"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
"github.com/micro/go-micro/v3/codec"
|
|
||||||
"github.com/micro/go-micro/v3/codec/jsonrpc"
|
|
||||||
"github.com/micro/go-micro/v3/codec/protorpc"
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
|
||||||
"github.com/micro/go-micro/v3/util/qson"
|
|
||||||
"github.com/oxtoacart/bpool"
|
"github.com/oxtoacart/bpool"
|
||||||
|
jsonrpc "github.com/unistack-org/micro-codec-jsonrpc"
|
||||||
|
protorpc "github.com/unistack-org/micro-codec-protorpc"
|
||||||
|
"github.com/unistack-org/micro/v3/api"
|
||||||
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
|
"github.com/unistack-org/micro/v3/api/internal/proto"
|
||||||
|
"github.com/unistack-org/micro/v3/client"
|
||||||
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
|
"github.com/unistack-org/micro/v3/errors"
|
||||||
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
|
"github.com/unistack-org/micro/v3/metadata"
|
||||||
|
"github.com/unistack-org/micro/v3/util/ctx"
|
||||||
|
"github.com/unistack-org/micro/v3/util/qson"
|
||||||
|
"github.com/unistack-org/micro/v3/util/router"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -113,7 +113,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// create custom router
|
// create custom router
|
||||||
callOpt := client.WithRouter(util.Router(service.Services))
|
callOpt := client.WithRouter(router.New(service.Services))
|
||||||
|
|
||||||
// walk the standard call path
|
// walk the standard call path
|
||||||
// get payload
|
// get payload
|
||||||
@@ -224,7 +224,7 @@ func requestPayload(r *http.Request) ([]byte, error) {
|
|||||||
case strings.Contains(ct, "application/json-rpc"):
|
case strings.Contains(ct, "application/json-rpc"):
|
||||||
msg := codec.Message{
|
msg := codec.Message{
|
||||||
Type: codec.Request,
|
Type: codec.Request,
|
||||||
Header: make(map[string]string),
|
Header: metadata.New(0),
|
||||||
}
|
}
|
||||||
c := jsonrpc.NewCodec(&buffer{r.Body})
|
c := jsonrpc.NewCodec(&buffer{r.Body})
|
||||||
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
||||||
@@ -238,7 +238,7 @@ func requestPayload(r *http.Request) ([]byte, error) {
|
|||||||
case strings.Contains(ct, "application/proto-rpc"), strings.Contains(ct, "application/octet-stream"):
|
case strings.Contains(ct, "application/proto-rpc"), strings.Contains(ct, "application/octet-stream"):
|
||||||
msg := codec.Message{
|
msg := codec.Message{
|
||||||
Type: codec.Request,
|
Type: codec.Request,
|
||||||
Header: make(map[string]string),
|
Header: metadata.New(0),
|
||||||
}
|
}
|
||||||
c := protorpc.NewCodec(&buffer{r.Body})
|
c := protorpc.NewCodec(&buffer{r.Body})
|
||||||
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
||||||
@@ -250,10 +250,12 @@ func requestPayload(r *http.Request) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
return raw.Marshal()
|
return raw.Marshal()
|
||||||
case strings.Contains(ct, "application/www-x-form-urlencoded"):
|
case strings.Contains(ct, "application/www-x-form-urlencoded"):
|
||||||
r.ParseForm()
|
if err = r.ParseForm(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// generate a new set of values from the form
|
// generate a new set of values from the form
|
||||||
vals := make(map[string]string)
|
vals := make(map[string]string, len(r.Form))
|
||||||
for k, v := range r.Form {
|
for k, v := range r.Form {
|
||||||
vals[k] = strings.Join(v, ",")
|
vals[k] = strings.Join(v, ",")
|
||||||
}
|
}
|
||||||
@@ -268,7 +270,7 @@ func requestPayload(r *http.Request) ([]byte, error) {
|
|||||||
// dont user metadata.FromContext as it mangles names
|
// dont user metadata.FromContext as it mangles names
|
||||||
md, ok := metadata.FromContext(ctx)
|
md, ok := metadata.FromContext(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
md = make(map[string]string)
|
md = metadata.New(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// allocate maximum
|
// allocate maximum
|
||||||
@@ -444,8 +446,8 @@ func writeError(w http.ResponseWriter, r *http.Request, err error) {
|
|||||||
|
|
||||||
_, werr := w.Write([]byte(ce.Error()))
|
_, werr := w.Write([]byte(ce.Error()))
|
||||||
if werr != nil {
|
if werr != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(werr)
|
logger.Error(werr.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -470,8 +472,8 @@ func writeResponse(w http.ResponseWriter, r *http.Request, rsp []byte) {
|
|||||||
// write response
|
// write response
|
||||||
_, err := w.Write(rsp)
|
_, err := w.Write(rsp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ package rpc
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/golang/protobuf/proto"
|
go_api "github.com/unistack-org/micro/v3/api/proto"
|
||||||
go_api "github.com/micro/go-micro/v3/api/proto"
|
jsonpb "google.golang.org/protobuf/encoding/protojson"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRequestPayloadFromRequest(t *testing.T) {
|
func TestRequestPayloadFromRequest(t *testing.T) {
|
||||||
@@ -22,7 +22,7 @@ func TestRequestPayloadFromRequest(t *testing.T) {
|
|||||||
t.Fatal("Failed to marshal proto", err)
|
t.Fatal("Failed to marshal proto", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonBytes, err := json.Marshal(protoEvent)
|
jsonBytes, err := jsonpb.Marshal(&protoEvent)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("Failed to marshal proto to JSON ", err)
|
t.Fatal("Failed to marshal proto to JSON ", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ import (
|
|||||||
"github.com/gobwas/httphead"
|
"github.com/gobwas/httphead"
|
||||||
"github.com/gobwas/ws"
|
"github.com/gobwas/ws"
|
||||||
"github.com/gobwas/ws/wsutil"
|
"github.com/gobwas/ws/wsutil"
|
||||||
"github.com/micro/go-micro/v3/api"
|
raw "github.com/unistack-org/micro-codec-bytes"
|
||||||
"github.com/micro/go-micro/v3/api/handler/util"
|
"github.com/unistack-org/micro/v3/api"
|
||||||
"github.com/micro/go-micro/v3/client"
|
"github.com/unistack-org/micro/v3/client"
|
||||||
raw "github.com/micro/go-micro/v3/codec/bytes"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
"github.com/micro/go-micro/v3/logger"
|
"github.com/unistack-org/micro/v3/util/router"
|
||||||
)
|
)
|
||||||
|
|
||||||
// serveWebsocket will stream rpc back over websockets assuming json
|
// serveWebsocket will stream rpc back over websockets assuming json
|
||||||
@@ -44,13 +44,15 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request,
|
|||||||
case "binary":
|
case "binary":
|
||||||
hdr["Sec-WebSocket-Protocol"] = []string{"binary"}
|
hdr["Sec-WebSocket-Protocol"] = []string{"binary"}
|
||||||
op = ws.OpBinary
|
op = ws.OpBinary
|
||||||
|
default:
|
||||||
|
op = ws.OpBinary
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
payload, err := requestPayload(r)
|
payload, err := requestPayload(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -72,16 +74,16 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request,
|
|||||||
|
|
||||||
conn, rw, _, err := upgrader.Upgrade(r, w)
|
conn, rw, _, err := upgrader.Upgrade(r, w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := conn.Close(); err != nil {
|
if err := conn.Close(); err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -111,21 +113,21 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request,
|
|||||||
)
|
)
|
||||||
|
|
||||||
// create custom router
|
// create custom router
|
||||||
callOpt := client.WithRouter(util.Router(service.Services))
|
callOpt := client.WithRouter(router.New(service.Services))
|
||||||
|
|
||||||
// create a new stream
|
// create a new stream
|
||||||
stream, err := c.Stream(ctx, req, callOpt)
|
stream, err := c.Stream(ctx, req, callOpt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if request != nil {
|
if request != nil {
|
||||||
if err = stream.Send(request); err != nil {
|
if err = stream.Send(request); err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -150,22 +152,22 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request,
|
|||||||
if strings.Contains(err.Error(), "context canceled") {
|
if strings.Contains(err.Error(), "context canceled") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// write the response
|
// write the response
|
||||||
if err := wsutil.WriteServerMessage(rw, op, buf); err != nil {
|
if err := wsutil.WriteServerMessage(rw, op, buf); err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err = rw.Flush(); err != nil {
|
if err = rw.Flush(); err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -195,8 +197,8 @@ func writeLoop(rw io.ReadWriter, stream client.Stream) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -212,8 +214,8 @@ func writeLoop(rw io.ReadWriter, stream client.Stream) {
|
|||||||
// if the extracted payload isn't empty lets use it
|
// if the extracted payload isn't empty lets use it
|
||||||
request := &raw.Frame{Data: buf}
|
request := &raw.Frame{Data: buf}
|
||||||
if err := stream.Send(request); err != nil {
|
if err := stream.Send(request); err != nil {
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
if logger.V(logger.ErrorLevel) {
|
||||||
logger.Error(err)
|
logger.Error(err.Error())
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
"github.com/unistack-org/micro/v3/api"
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
"github.com/unistack-org/micro/v3/api/handler"
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -72,10 +72,11 @@ func (wh *webHandler) getService(r *http.Request) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// get the nodes
|
// get the nodes
|
||||||
var nodes []*registry.Node
|
nodes := make([]*registry.Node, 0, len(service.Services))
|
||||||
for _, srv := range service.Services {
|
for _, srv := range service.Services {
|
||||||
nodes = append(nodes, srv.Nodes...)
|
nodes = append(nodes, srv.Nodes...)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(nodes) == 0 {
|
if len(nodes) == 0 {
|
||||||
return "", errors.New("no route found")
|
return "", errors.New("no route found")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,68 +1,81 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// protoc-gen-go v1.25.0
|
||||||
|
// protoc v3.6.1
|
||||||
// source: api/proto/api.proto
|
// source: api/proto/api.proto
|
||||||
|
|
||||||
package go_api
|
package go_api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
proto "github.com/golang/protobuf/proto"
|
||||||
math "math"
|
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||||
|
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||||
|
reflect "reflect"
|
||||||
|
sync "sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
const (
|
||||||
var _ = proto.Marshal
|
// Verify that this generated code is sufficiently up-to-date.
|
||||||
var _ = fmt.Errorf
|
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||||
var _ = math.Inf
|
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||||
|
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||||
|
)
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||||
// is compatible with the proto package it is being compiled against.
|
// of the legacy proto package is being used.
|
||||||
// A compilation error at this line likely means your copy of the
|
const _ = proto.ProtoPackageIsVersion4
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
type Pair struct {
|
type Pair struct {
|
||||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
state protoimpl.MessageState
|
||||||
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
sizeCache protoimpl.SizeCache
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
unknownFields protoimpl.UnknownFields
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
||||||
|
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Pair) Reset() { *m = Pair{} }
|
func (x *Pair) Reset() {
|
||||||
func (m *Pair) String() string { return proto.CompactTextString(m) }
|
*x = Pair{}
|
||||||
func (*Pair) ProtoMessage() {}
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Pair) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Pair) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Pair) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Pair.ProtoReflect.Descriptor instead.
|
||||||
func (*Pair) Descriptor() ([]byte, []int) {
|
func (*Pair) Descriptor() ([]byte, []int) {
|
||||||
return fileDescriptor_2df576b66d12087a, []int{0}
|
return file_api_proto_api_proto_rawDescGZIP(), []int{0}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Pair) XXX_Unmarshal(b []byte) error {
|
func (x *Pair) GetKey() string {
|
||||||
return xxx_messageInfo_Pair.Unmarshal(m, b)
|
if x != nil {
|
||||||
}
|
return x.Key
|
||||||
func (m *Pair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Pair.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Pair.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Pair.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Pair.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Pair proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Pair) GetKey() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Key
|
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Pair) GetValues() []string {
|
func (x *Pair) GetValues() []string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Values
|
return x.Values
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -70,88 +83,96 @@ func (m *Pair) GetValues() []string {
|
|||||||
// A HTTP request as RPC
|
// A HTTP request as RPC
|
||||||
// Forward by the api handler
|
// Forward by the api handler
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
state protoimpl.MessageState
|
||||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
sizeCache protoimpl.SizeCache
|
||||||
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
unknownFields protoimpl.UnknownFields
|
||||||
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
||||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"`
|
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||||
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||||
XXX_unrecognized []byte `json:"-"`
|
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||||
XXX_sizecache int32 `json:"-"`
|
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"` // raw request body; if not application/x-www-form-urlencoded
|
||||||
|
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) Reset() { *m = Request{} }
|
func (x *Request) Reset() {
|
||||||
func (m *Request) String() string { return proto.CompactTextString(m) }
|
*x = Request{}
|
||||||
func (*Request) ProtoMessage() {}
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Request) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Request) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Request) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
|
||||||
func (*Request) Descriptor() ([]byte, []int) {
|
func (*Request) Descriptor() ([]byte, []int) {
|
||||||
return fileDescriptor_2df576b66d12087a, []int{1}
|
return file_api_proto_api_proto_rawDescGZIP(), []int{1}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) XXX_Unmarshal(b []byte) error {
|
func (x *Request) GetMethod() string {
|
||||||
return xxx_messageInfo_Request.Unmarshal(m, b)
|
if x != nil {
|
||||||
}
|
return x.Method
|
||||||
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Request.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Request.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Request.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Request.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Request proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Request) GetMethod() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Method
|
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetPath() string {
|
func (x *Request) GetPath() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Path
|
return x.Path
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetHeader() map[string]*Pair {
|
func (x *Request) GetHeader() map[string]*Pair {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Header
|
return x.Header
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetGet() map[string]*Pair {
|
func (x *Request) GetGet() map[string]*Pair {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Get
|
return x.Get
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetPost() map[string]*Pair {
|
func (x *Request) GetPost() map[string]*Pair {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Post
|
return x.Post
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetBody() string {
|
func (x *Request) GetBody() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Body
|
return x.Body
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Request) GetUrl() string {
|
func (x *Request) GetUrl() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Url
|
return x.Url
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -159,56 +180,64 @@ func (m *Request) GetUrl() string {
|
|||||||
// A HTTP response as RPC
|
// A HTTP response as RPC
|
||||||
// Expected response for the api handler
|
// Expected response for the api handler
|
||||||
type Response struct {
|
type Response struct {
|
||||||
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
state protoimpl.MessageState
|
||||||
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
sizeCache protoimpl.SizeCache
|
||||||
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
unknownFields protoimpl.UnknownFields
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
||||||
XXX_sizecache int32 `json:"-"`
|
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||||
|
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Response) Reset() { *m = Response{} }
|
func (x *Response) Reset() {
|
||||||
func (m *Response) String() string { return proto.CompactTextString(m) }
|
*x = Response{}
|
||||||
func (*Response) ProtoMessage() {}
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Response) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Response) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Response) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
|
||||||
func (*Response) Descriptor() ([]byte, []int) {
|
func (*Response) Descriptor() ([]byte, []int) {
|
||||||
return fileDescriptor_2df576b66d12087a, []int{2}
|
return file_api_proto_api_proto_rawDescGZIP(), []int{2}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Response) XXX_Unmarshal(b []byte) error {
|
func (x *Response) GetStatusCode() int32 {
|
||||||
return xxx_messageInfo_Response.Unmarshal(m, b)
|
if x != nil {
|
||||||
}
|
return x.StatusCode
|
||||||
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Response.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Response.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Response.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Response proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Response) GetStatusCode() int32 {
|
|
||||||
if m != nil {
|
|
||||||
return m.StatusCode
|
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Response) GetHeader() map[string]*Pair {
|
func (x *Response) GetHeader() map[string]*Pair {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Header
|
return x.Header
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Response) GetBody() string {
|
func (x *Response) GetBody() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Body
|
return x.Body
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -216,6 +245,10 @@ func (m *Response) GetBody() string {
|
|||||||
// A HTTP event as RPC
|
// A HTTP event as RPC
|
||||||
// Forwarded by the event handler
|
// Forwarded by the event handler
|
||||||
type Event struct {
|
type Event struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
// e.g login
|
// e.g login
|
||||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||||
// uuid
|
// uuid
|
||||||
@@ -225,111 +258,254 @@ type Event struct {
|
|||||||
// event headers
|
// event headers
|
||||||
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||||
// the event data
|
// the event data
|
||||||
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) Reset() { *m = Event{} }
|
func (x *Event) Reset() {
|
||||||
func (m *Event) String() string { return proto.CompactTextString(m) }
|
*x = Event{}
|
||||||
func (*Event) ProtoMessage() {}
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Event) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Event) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Event) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Event.ProtoReflect.Descriptor instead.
|
||||||
func (*Event) Descriptor() ([]byte, []int) {
|
func (*Event) Descriptor() ([]byte, []int) {
|
||||||
return fileDescriptor_2df576b66d12087a, []int{3}
|
return file_api_proto_api_proto_rawDescGZIP(), []int{3}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) XXX_Unmarshal(b []byte) error {
|
func (x *Event) GetName() string {
|
||||||
return xxx_messageInfo_Event.Unmarshal(m, b)
|
if x != nil {
|
||||||
}
|
return x.Name
|
||||||
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Event.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Event.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Event.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Event proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Event) GetName() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Name
|
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) GetId() string {
|
func (x *Event) GetId() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Id
|
return x.Id
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) GetTimestamp() int64 {
|
func (x *Event) GetTimestamp() int64 {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Timestamp
|
return x.Timestamp
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) GetHeader() map[string]*Pair {
|
func (x *Event) GetHeader() map[string]*Pair {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Header
|
return x.Header
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Event) GetData() string {
|
func (x *Event) GetData() string {
|
||||||
if m != nil {
|
if x != nil {
|
||||||
return m.Data
|
return x.Data
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
var File_api_proto_api_proto protoreflect.FileDescriptor
|
||||||
proto.RegisterType((*Pair)(nil), "go.api.Pair")
|
|
||||||
proto.RegisterType((*Request)(nil), "go.api.Request")
|
var file_api_proto_api_proto_rawDesc = []byte{
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.GetEntry")
|
0x0a, 0x13, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2e,
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.HeaderEntry")
|
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x22, 0x30, 0x0a,
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.PostEntry")
|
0x04, 0x50, 0x61, 0x69, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||||
proto.RegisterType((*Response)(nil), "go.api.Response")
|
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Response.HeaderEntry")
|
0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x22,
|
||||||
proto.RegisterType((*Event)(nil), "go.api.Event")
|
0xc1, 0x03, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x6d,
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Event.HeaderEntry")
|
0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, 0x65, 0x74,
|
||||||
|
0x68, 0x6f, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28,
|
||||||
|
0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x33, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65,
|
||||||
|
0x72, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69,
|
||||||
|
0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45,
|
||||||
|
0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x03,
|
||||||
|
0x67, 0x65, 0x74, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x67, 0x6f, 0x2e, 0x61,
|
||||||
|
0x70, 0x69, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x6e,
|
||||||
|
0x74, 0x72, 0x79, 0x52, 0x03, 0x67, 0x65, 0x74, 0x12, 0x2d, 0x0a, 0x04, 0x70, 0x6f, 0x73, 0x74,
|
||||||
|
0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||||
|
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72,
|
||||||
|
0x79, 0x52, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18,
|
||||||
|
0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x75,
|
||||||
|
0x72, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x1a, 0x47, 0x0a,
|
||||||
|
0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03,
|
||||||
|
0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22,
|
||||||
|
0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e,
|
||||||
|
0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c,
|
||||||
|
0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x44, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x45, 0x6e, 0x74,
|
||||||
|
0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||||
|
0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20,
|
||||||
|
0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69,
|
||||||
|
0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x45, 0x0a, 0x09,
|
||||||
|
0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||||
|
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||||
|
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||||
|
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||||
|
0x02, 0x38, 0x01, 0x22, 0xbd, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
|
||||||
|
0x12, 0x1e, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x01,
|
||||||
|
0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65,
|
||||||
|
0x12, 0x34, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b,
|
||||||
|
0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||||
|
0x73, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06,
|
||||||
|
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x03,
|
||||||
|
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65,
|
||||||
|
0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||||
|
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||||
|
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||||
|
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||||
|
0x02, 0x38, 0x01, 0x22, 0xd9, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a,
|
||||||
|
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
|
||||||
|
0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69,
|
||||||
|
0x64, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03,
|
||||||
|
0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12,
|
||||||
|
0x31, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32,
|
||||||
|
0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x48,
|
||||||
|
0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64,
|
||||||
|
0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09,
|
||||||
|
0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72,
|
||||||
|
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||||
|
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||||
|
0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||||
|
0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x62,
|
||||||
|
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() { proto.RegisterFile("api/proto/api.proto", fileDescriptor_2df576b66d12087a) }
|
var (
|
||||||
|
file_api_proto_api_proto_rawDescOnce sync.Once
|
||||||
|
file_api_proto_api_proto_rawDescData = file_api_proto_api_proto_rawDesc
|
||||||
|
)
|
||||||
|
|
||||||
var fileDescriptor_2df576b66d12087a = []byte{
|
func file_api_proto_api_proto_rawDescGZIP() []byte {
|
||||||
// 393 bytes of a gzipped FileDescriptorProto
|
file_api_proto_api_proto_rawDescOnce.Do(func() {
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0xcd, 0xce, 0xd3, 0x30,
|
file_api_proto_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_api_proto_api_proto_rawDescData)
|
||||||
0x10, 0x54, 0xe2, 0x24, 0x6d, 0xb6, 0x08, 0x21, 0x23, 0x21, 0x53, 0x2a, 0x54, 0xe5, 0x54, 0x21,
|
})
|
||||||
0x91, 0x42, 0xcb, 0x01, 0x71, 0x85, 0xaa, 0x1c, 0x2b, 0xbf, 0x81, 0xab, 0x58, 0x6d, 0x44, 0x13,
|
return file_api_proto_api_proto_rawDescData
|
||||||
0x9b, 0xd8, 0xa9, 0xd4, 0x87, 0xe3, 0xc0, 0x63, 0xf0, 0x36, 0xc8, 0x1b, 0xf7, 0xe7, 0xab, 0xfa,
|
}
|
||||||
0x5d, 0xbe, 0xaf, 0xb7, 0x89, 0x3d, 0x3b, 0x3b, 0x3b, 0xeb, 0xc0, 0x6b, 0xa1, 0xcb, 0xa9, 0x6e,
|
|
||||||
0x94, 0x55, 0x53, 0xa1, 0xcb, 0x1c, 0x11, 0x4d, 0x36, 0x2a, 0x17, 0xba, 0xcc, 0x3e, 0x41, 0xb4,
|
var file_api_proto_api_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
|
||||||
0x12, 0x65, 0x43, 0x5f, 0x01, 0xf9, 0x25, 0x0f, 0x2c, 0x18, 0x07, 0x93, 0x94, 0x3b, 0x48, 0xdf,
|
var file_api_proto_api_proto_goTypes = []interface{}{
|
||||||
0x40, 0xb2, 0x17, 0xbb, 0x56, 0x1a, 0x16, 0x8e, 0xc9, 0x24, 0xe5, 0xfe, 0x2b, 0xfb, 0x4b, 0xa0,
|
(*Pair)(nil), // 0: go.api.Pair
|
||||||
0xc7, 0xe5, 0xef, 0x56, 0x1a, 0xeb, 0x38, 0x95, 0xb4, 0x5b, 0x55, 0xf8, 0x42, 0xff, 0x45, 0x29,
|
(*Request)(nil), // 1: go.api.Request
|
||||||
0x44, 0x5a, 0xd8, 0x2d, 0x0b, 0xf1, 0x14, 0x31, 0x9d, 0x43, 0xb2, 0x95, 0xa2, 0x90, 0x0d, 0x23,
|
(*Response)(nil), // 2: go.api.Response
|
||||||
0x63, 0x32, 0x19, 0xcc, 0xde, 0xe5, 0x9d, 0x85, 0xdc, 0x8b, 0xe5, 0x3f, 0xf1, 0x76, 0x51, 0xdb,
|
(*Event)(nil), // 3: go.api.Event
|
||||||
0xe6, 0xc0, 0x3d, 0x95, 0x7e, 0x00, 0xb2, 0x91, 0x96, 0x45, 0x58, 0xc1, 0xae, 0x2b, 0x96, 0xd2,
|
nil, // 4: go.api.Request.HeaderEntry
|
||||||
0x76, 0x74, 0x47, 0xa2, 0x1f, 0x21, 0xd2, 0xca, 0x58, 0x16, 0x23, 0xf9, 0xed, 0x35, 0x79, 0xa5,
|
nil, // 5: go.api.Request.GetEntry
|
||||||
0x8c, 0x67, 0x23, 0xcd, 0x79, 0x5c, 0xab, 0xe2, 0xc0, 0x92, 0xce, 0xa3, 0xc3, 0x2e, 0x85, 0xb6,
|
nil, // 6: go.api.Request.PostEntry
|
||||||
0xd9, 0xb1, 0x5e, 0x97, 0x42, 0xdb, 0xec, 0x86, 0x4b, 0x18, 0x5c, 0xf8, 0xba, 0x11, 0x53, 0x06,
|
nil, // 7: go.api.Response.HeaderEntry
|
||||||
0x31, 0x06, 0x83, 0xb3, 0x0e, 0x66, 0x2f, 0x8e, 0x6d, 0x5d, 0xaa, 0xbc, 0xbb, 0xfa, 0x16, 0x7e,
|
nil, // 8: go.api.Event.HeaderEntry
|
||||||
0x0d, 0x86, 0x3f, 0xa0, 0x7f, 0xb4, 0xfb, 0x0c, 0x95, 0x05, 0xa4, 0xa7, 0x39, 0x9e, 0x2e, 0x93,
|
}
|
||||||
0xfd, 0x09, 0xa0, 0xcf, 0xa5, 0xd1, 0xaa, 0x36, 0x92, 0xbe, 0x07, 0x30, 0x56, 0xd8, 0xd6, 0x7c,
|
var file_api_proto_api_proto_depIdxs = []int32{
|
||||||
0x57, 0x85, 0x44, 0xb5, 0x98, 0x5f, 0x9c, 0xd0, 0x2f, 0xa7, 0xc5, 0x85, 0x98, 0xec, 0xe8, 0x9c,
|
4, // 0: go.api.Request.header:type_name -> go.api.Request.HeaderEntry
|
||||||
0x6c, 0xa7, 0x70, 0x73, 0x73, 0xc7, 0x78, 0xc9, 0x39, 0xde, 0xbb, 0x85, 0x99, 0xfd, 0x0b, 0x20,
|
5, // 1: go.api.Request.get:type_name -> go.api.Request.GetEntry
|
||||||
0x5e, 0xec, 0x65, 0x8d, 0x5b, 0xac, 0x45, 0x25, 0xbd, 0x08, 0x62, 0xfa, 0x12, 0xc2, 0xb2, 0xf0,
|
6, // 2: go.api.Request.post:type_name -> go.api.Request.PostEntry
|
||||||
0x6f, 0x2f, 0x2c, 0x0b, 0x3a, 0x82, 0xd4, 0x96, 0x95, 0x34, 0x56, 0x54, 0x1a, 0xfd, 0x10, 0x7e,
|
7, // 3: go.api.Response.header:type_name -> go.api.Response.HeaderEntry
|
||||||
0x3e, 0xa0, 0x9f, 0x4f, 0xe3, 0x45, 0x0f, 0x1f, 0x0e, 0x36, 0x78, 0x6c, 0xb6, 0x42, 0x58, 0xc1,
|
8, // 4: go.api.Event.header:type_name -> go.api.Event.HeaderEntry
|
||||||
0xe2, 0xae, 0xa9, 0xc3, 0x77, 0x9b, 0x6d, 0x9d, 0xe0, 0x0f, 0x3a, 0xff, 0x1f, 0x00, 0x00, 0xff,
|
0, // 5: go.api.Request.HeaderEntry.value:type_name -> go.api.Pair
|
||||||
0xff, 0xd4, 0x6d, 0x70, 0x51, 0xb7, 0x03, 0x00, 0x00,
|
0, // 6: go.api.Request.GetEntry.value:type_name -> go.api.Pair
|
||||||
|
0, // 7: go.api.Request.PostEntry.value:type_name -> go.api.Pair
|
||||||
|
0, // 8: go.api.Response.HeaderEntry.value:type_name -> go.api.Pair
|
||||||
|
0, // 9: go.api.Event.HeaderEntry.value:type_name -> go.api.Pair
|
||||||
|
10, // [10:10] is the sub-list for method output_type
|
||||||
|
10, // [10:10] is the sub-list for method input_type
|
||||||
|
10, // [10:10] is the sub-list for extension type_name
|
||||||
|
10, // [10:10] is the sub-list for extension extendee
|
||||||
|
0, // [0:10] is the sub-list for field type_name
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() { file_api_proto_api_proto_init() }
|
||||||
|
func file_api_proto_api_proto_init() {
|
||||||
|
if File_api_proto_api_proto != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !protoimpl.UnsafeEnabled {
|
||||||
|
file_api_proto_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*Pair); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_api_proto_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*Request); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_api_proto_api_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*Response); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_api_proto_api_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*Event); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
type x struct{}
|
||||||
|
out := protoimpl.TypeBuilder{
|
||||||
|
File: protoimpl.DescBuilder{
|
||||||
|
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||||
|
RawDescriptor: file_api_proto_api_proto_rawDesc,
|
||||||
|
NumEnums: 0,
|
||||||
|
NumMessages: 9,
|
||||||
|
NumExtensions: 0,
|
||||||
|
NumServices: 0,
|
||||||
|
},
|
||||||
|
GoTypes: file_api_proto_api_proto_goTypes,
|
||||||
|
DependencyIndexes: file_api_proto_api_proto_depIdxs,
|
||||||
|
MessageInfos: file_api_proto_api_proto_msgTypes,
|
||||||
|
}.Build()
|
||||||
|
File_api_proto_api_proto = out.File
|
||||||
|
file_api_proto_api_proto_rawDesc = nil
|
||||||
|
file_api_proto_api_proto_goTypes = nil
|
||||||
|
file_api_proto_api_proto_depIdxs = nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,15 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Resolver struct
|
||||||
type Resolver struct {
|
type Resolver struct {
|
||||||
opts resolver.Options
|
opts resolver.Options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolve func to resolve enndpoint
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||||
// parse options
|
// parse options
|
||||||
options := resolver.NewResolveOptions(opts...)
|
options := resolver.NewResolveOptions(opts...)
|
||||||
@@ -39,6 +41,7 @@ func (r *Resolver) String() string {
|
|||||||
return "grpc"
|
return "grpc"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewResolver is used to create new Resolver
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package host
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Resolver struct {
|
type Resolver struct {
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
package resolver
|
package resolver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Options struct
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Handler string
|
Handler string
|
||||||
ServicePrefix string
|
ServicePrefix string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Option func
|
||||||
type Option func(o *Options)
|
type Option func(o *Options)
|
||||||
|
|
||||||
// WithHandler sets the handler being used
|
// WithHandler sets the handler being used
|
||||||
@@ -27,7 +29,7 @@ func WithServicePrefix(p string) Option {
|
|||||||
|
|
||||||
// NewOptions returns new initialised options
|
// NewOptions returns new initialised options
|
||||||
func NewOptions(opts ...Option) Options {
|
func NewOptions(opts ...Option) Options {
|
||||||
var options Options
|
options := Options{}
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&options)
|
o(&options)
|
||||||
}
|
}
|
||||||
@@ -51,13 +53,10 @@ func Domain(n string) ResolveOption {
|
|||||||
|
|
||||||
// NewResolveOptions returns new initialised resolve options
|
// NewResolveOptions returns new initialised resolve options
|
||||||
func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
|
func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
|
||||||
var options ResolveOptions
|
options := ResolveOptions{Domain: registry.DefaultDomain}
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&options)
|
o(&options)
|
||||||
}
|
}
|
||||||
if len(options.Domain) == 0 {
|
|
||||||
options.Domain = registry.DefaultDomain
|
|
||||||
}
|
|
||||||
|
|
||||||
return options
|
return options
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Resolver struct {
|
type Resolver struct {
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrNotFound = errors.New("not found")
|
// ErrNotFound returned when endpoint is not found
|
||||||
|
ErrNotFound = errors.New("not found")
|
||||||
|
// ErrInvalidPath returned on invalid path
|
||||||
ErrInvalidPath = errors.New("invalid path")
|
ErrInvalidPath = errors.New("invalid path")
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,7 +21,7 @@ type Resolver interface {
|
|||||||
|
|
||||||
// Endpoint is the endpoint for a http request
|
// Endpoint is the endpoint for a http request
|
||||||
type Endpoint struct {
|
type Endpoint struct {
|
||||||
// e.g greeter
|
// Endpoint name e.g greeter
|
||||||
Name string
|
Name string
|
||||||
// HTTP Host e.g example.com
|
// HTTP Host e.g example.com
|
||||||
Host string
|
Host string
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
"github.com/micro/go-micro/v3/logger"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ func (r *Resolver) Domain(req *http.Request) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// check for dev enviroment
|
// check for dev environment
|
||||||
if host == "localhost" || host == "127.0.0.1" {
|
if host == "localhost" || host == "127.0.0.1" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,9 @@ func (r *Resolver) Domain(req *http.Request) string {
|
|||||||
// extract the top level domain plus one (e.g. 'myapp.com')
|
// extract the top level domain plus one (e.g. 'myapp.com')
|
||||||
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
|
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Debugf("Unable to extract domain from %v", host)
|
if logger.V(logger.DebugLevel) {
|
||||||
|
logger.Debug("Unable to extract domain from %v", host)
|
||||||
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +68,11 @@ func (r *Resolver) Domain(req *http.Request) string {
|
|||||||
// remove the domain from the host, leaving the subdomain, e.g. "staging.foo.myapp.com" => "staging.foo"
|
// remove the domain from the host, leaving the subdomain, e.g. "staging.foo.myapp.com" => "staging.foo"
|
||||||
subdomain := strings.TrimSuffix(host, "."+domain)
|
subdomain := strings.TrimSuffix(host, "."+domain)
|
||||||
|
|
||||||
|
// ignore the API subdomain
|
||||||
|
if subdomain == "api" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// return the reversed subdomain as the namespace, e.g. "staging.foo" => "foo-staging"
|
// return the reversed subdomain as the namespace, e.g. "staging.foo" => "foo-staging"
|
||||||
comps := strings.Split(subdomain, ".")
|
comps := strings.Split(subdomain, ".")
|
||||||
for i := len(comps)/2 - 1; i >= 0; i-- {
|
for i := len(comps)/2 - 1; i >= 0; i-- {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"context"
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||||
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Handler string
|
Handler string
|
||||||
Registry registry.Registry
|
Registry registry.Registry
|
||||||
Resolver resolver.Resolver
|
Resolver resolver.Resolver
|
||||||
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(o *Options)
|
type Option func(o *Options)
|
||||||
|
|
||||||
func NewOptions(opts ...Option) Options {
|
func NewOptions(opts ...Option) Options {
|
||||||
options := Options{
|
options := Options{
|
||||||
Handler: "meta",
|
Context: context.Background(),
|
||||||
Registry: mdns.NewRegistry(),
|
Handler: "meta",
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
@@ -34,18 +36,28 @@ func NewOptions(opts ...Option) Options {
|
|||||||
return options
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithContext sets the context
|
||||||
|
func WithContext(ctx context.Context) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
o.Context = ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithHandler sets the handler
|
||||||
func WithHandler(h string) Option {
|
func WithHandler(h string) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Handler = h
|
o.Handler = h
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithRegistry sets the registry
|
||||||
func WithRegistry(r registry.Registry) Option {
|
func WithRegistry(r registry.Registry) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Registry = r
|
o.Registry = r
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithResolver sets the resolver
|
||||||
func WithResolver(r resolver.Resolver) Option {
|
func WithResolver(r resolver.Resolver) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Resolver = r
|
o.Resolver = r
|
||||||
|
|||||||
@@ -1,498 +0,0 @@
|
|||||||
// Package registry provides a dynamic api service router
|
|
||||||
package registry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
"github.com/micro/go-micro/v3/api/router/util"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/cache"
|
|
||||||
)
|
|
||||||
|
|
||||||
// endpoint struct, that holds compiled pcre
|
|
||||||
type endpoint struct {
|
|
||||||
hostregs []*regexp.Regexp
|
|
||||||
pathregs []util.Pattern
|
|
||||||
pcreregs []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
// router is the default router
|
|
||||||
type registryRouter struct {
|
|
||||||
exit chan bool
|
|
||||||
opts router.Options
|
|
||||||
|
|
||||||
// registry cache
|
|
||||||
rc cache.Cache
|
|
||||||
|
|
||||||
sync.RWMutex
|
|
||||||
eps map[string]*api.Service
|
|
||||||
// compiled regexp for host and path
|
|
||||||
ceps map[string]*endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) isClosed() bool {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// refresh list of api services
|
|
||||||
func (r *registryRouter) refresh() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
services, err := r.opts.Registry.ListServices()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to list services: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
// for each service, get service and store endpoints
|
|
||||||
for _, s := range services {
|
|
||||||
service, err := r.rc.GetService(s.Name)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to get service: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
r.store(service)
|
|
||||||
}
|
|
||||||
|
|
||||||
// refresh list in 10 minutes... cruft
|
|
||||||
// use registry watching
|
|
||||||
select {
|
|
||||||
case <-time.After(time.Minute * 10):
|
|
||||||
case <-r.exit:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// process watch event
|
|
||||||
func (r *registryRouter) process(res *registry.Result) {
|
|
||||||
// skip these things
|
|
||||||
if res == nil || res.Service == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// get entry from cache
|
|
||||||
service, err := r.rc.GetService(res.Service.Name)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to get %v service: %v", res.Service.Name, err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// update our local endpoints
|
|
||||||
r.store(service)
|
|
||||||
}
|
|
||||||
|
|
||||||
// store local endpoint cache
|
|
||||||
func (r *registryRouter) store(services []*registry.Service) {
|
|
||||||
// endpoints
|
|
||||||
eps := map[string]*api.Service{}
|
|
||||||
|
|
||||||
// services
|
|
||||||
names := map[string]bool{}
|
|
||||||
|
|
||||||
// create a new endpoint mapping
|
|
||||||
for _, service := range services {
|
|
||||||
// set names we need later
|
|
||||||
names[service.Name] = true
|
|
||||||
|
|
||||||
// map per endpoint
|
|
||||||
for _, sep := range service.Endpoints {
|
|
||||||
// create a key service:endpoint_name
|
|
||||||
key := fmt.Sprintf("%s.%s", service.Name, sep.Name)
|
|
||||||
// decode endpoint
|
|
||||||
end := api.Decode(sep.Metadata)
|
|
||||||
|
|
||||||
// if we got nothing skip
|
|
||||||
if err := api.Validate(end); err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint validation failed: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get endpoint
|
|
||||||
ep, ok := eps[key]
|
|
||||||
if !ok {
|
|
||||||
ep = &api.Service{Name: service.Name}
|
|
||||||
}
|
|
||||||
|
|
||||||
// overwrite the endpoint
|
|
||||||
ep.Endpoint = end
|
|
||||||
// append services
|
|
||||||
ep.Services = append(ep.Services, service)
|
|
||||||
// store it
|
|
||||||
eps[key] = ep
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Lock()
|
|
||||||
defer r.Unlock()
|
|
||||||
|
|
||||||
// delete any existing eps for services we know
|
|
||||||
for key, service := range r.eps {
|
|
||||||
// skip what we don't care about
|
|
||||||
if !names[service.Name] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// ok we know this thing
|
|
||||||
// delete delete delete
|
|
||||||
delete(r.eps, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// now set the eps we have
|
|
||||||
for name, ep := range eps {
|
|
||||||
r.eps[name] = ep
|
|
||||||
cep := &endpoint{}
|
|
||||||
|
|
||||||
for _, h := range ep.Endpoint.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
hostreg, err := regexp.CompilePOSIX(h)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid host regexp: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
cep.hostregs = append(cep.hostregs, hostreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range ep.Endpoint.Path {
|
|
||||||
var pcreok bool
|
|
||||||
|
|
||||||
if p[0] == '^' && p[len(p)-1] == '$' {
|
|
||||||
pcrereg, err := regexp.CompilePOSIX(p)
|
|
||||||
if err == nil {
|
|
||||||
cep.pcreregs = append(cep.pcreregs, pcrereg)
|
|
||||||
pcreok = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rule, err := util.Parse(p)
|
|
||||||
if err != nil && !pcreok {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid path pattern: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
} else if err != nil && pcreok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
tpl := rule.Compile()
|
|
||||||
pathreg, err := util.NewPattern(tpl.Version, tpl.OpCodes, tpl.Pool, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid path pattern: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
cep.pathregs = append(cep.pathregs, pathreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.ceps[name] = cep
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for endpoint changes
|
|
||||||
func (r *registryRouter) watch() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
if r.isClosed() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for changes
|
|
||||||
w, err := r.opts.Registry.Watch()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("error watching endpoints: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan bool)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-ch:
|
|
||||||
w.Stop()
|
|
||||||
case <-r.exit:
|
|
||||||
w.Stop()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// reset if we get here
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
for {
|
|
||||||
// process next event
|
|
||||||
res, err := w.Next()
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("error getting next endpoint: %v", err)
|
|
||||||
}
|
|
||||||
close(ch)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
r.process(res)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Options() router.Options {
|
|
||||||
return r.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Close() error {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(r.exit)
|
|
||||||
r.rc.Stop()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Register(ep *api.Endpoint) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Deregister(ep *api.Endpoint) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.RLock()
|
|
||||||
defer r.RUnlock()
|
|
||||||
|
|
||||||
var idx int
|
|
||||||
if len(req.URL.Path) > 0 && req.URL.Path != "/" {
|
|
||||||
idx = 1
|
|
||||||
}
|
|
||||||
path := strings.Split(req.URL.Path[idx:], "/")
|
|
||||||
|
|
||||||
// use the first match
|
|
||||||
// TODO: weighted matching
|
|
||||||
for n, e := range r.eps {
|
|
||||||
cep, ok := r.ceps[n]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ep := e.Endpoint
|
|
||||||
var mMatch, hMatch, pMatch bool
|
|
||||||
// 1. try method
|
|
||||||
for _, m := range ep.Method {
|
|
||||||
if m == req.Method {
|
|
||||||
mMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !mMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api method match %s", req.Method)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. try host
|
|
||||||
if len(ep.Host) == 0 {
|
|
||||||
hMatch = true
|
|
||||||
} else {
|
|
||||||
for idx, h := range ep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if cep.hostregs[idx].MatchString(req.URL.Host) {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api host match %s", req.URL.Host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. try path via google.api path matching
|
|
||||||
for _, pathreg := range cep.pathregs {
|
|
||||||
matches, err := pathreg.Match(path, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath match %s = %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
ctx := req.Context()
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(metadata.Metadata)
|
|
||||||
}
|
|
||||||
for k, v := range matches {
|
|
||||||
md[fmt.Sprintf("x-api-field-%s", k)] = v
|
|
||||||
}
|
|
||||||
md["x-api-body"] = ep.Body
|
|
||||||
*req = *req.Clone(metadata.NewContext(ctx, md))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
// 4. try path via pcre path matching
|
|
||||||
for _, pathreg := range cep.pcreregs {
|
|
||||||
if !pathreg.MatchString(req.URL.Path) {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Percentage traffic
|
|
||||||
// we got here, so its a match
|
|
||||||
return e, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// no match
|
|
||||||
return nil, errors.New("not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Route(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get an endpoint
|
|
||||||
ep, err := r.Endpoint(req)
|
|
||||||
if err == nil {
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// error not nil
|
|
||||||
// ignore that shit
|
|
||||||
// TODO: don't ignore that shit
|
|
||||||
|
|
||||||
// get the service name
|
|
||||||
rp, err := r.opts.Resolver.Resolve(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// service name
|
|
||||||
name := rp.Name
|
|
||||||
|
|
||||||
// get service
|
|
||||||
services, err := r.rc.GetService(name, registry.GetDomain(rp.Domain))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// only use endpoint matching when the meta handler is set aka api.Default
|
|
||||||
switch r.opts.Handler {
|
|
||||||
// rpc handlers
|
|
||||||
case "meta", "api", "rpc":
|
|
||||||
handler := r.opts.Handler
|
|
||||||
|
|
||||||
// set default handler to api
|
|
||||||
if r.opts.Handler == "meta" {
|
|
||||||
handler = "rpc"
|
|
||||||
}
|
|
||||||
|
|
||||||
// construct api service
|
|
||||||
return &api.Service{
|
|
||||||
Name: name,
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: rp.Method,
|
|
||||||
Handler: handler,
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}, nil
|
|
||||||
// http handler
|
|
||||||
case "http", "proxy", "web":
|
|
||||||
// construct api service
|
|
||||||
return &api.Service{
|
|
||||||
Name: name,
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: req.URL.String(),
|
|
||||||
Handler: r.opts.Handler,
|
|
||||||
Host: []string{req.Host},
|
|
||||||
Method: []string{req.Method},
|
|
||||||
Path: []string{req.URL.Path},
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, errors.New("unknown handler")
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRouter(opts ...router.Option) *registryRouter {
|
|
||||||
options := router.NewOptions(opts...)
|
|
||||||
r := ®istryRouter{
|
|
||||||
exit: make(chan bool),
|
|
||||||
opts: options,
|
|
||||||
rc: cache.New(options.Registry),
|
|
||||||
eps: make(map[string]*api.Service),
|
|
||||||
ceps: make(map[string]*endpoint),
|
|
||||||
}
|
|
||||||
go r.watch()
|
|
||||||
go r.refresh()
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRouter returns the default router
|
|
||||||
func NewRouter(opts ...router.Option) router.Router {
|
|
||||||
return newRouter(opts...)
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package registry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestStoreRegex(t *testing.T) {
|
|
||||||
router := newRouter()
|
|
||||||
router.store([]*registry.Service{
|
|
||||||
{
|
|
||||||
Name: "Foobar",
|
|
||||||
Version: "latest",
|
|
||||||
Endpoints: []*registry.Endpoint{
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Metadata: map[string]string{
|
|
||||||
"endpoint": "FooEndpoint",
|
|
||||||
"description": "Some description",
|
|
||||||
"method": "POST",
|
|
||||||
"path": "^/foo/$",
|
|
||||||
"handler": "rpc",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Metadata: map[string]string{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Len(t, router.ceps["Foobar.foo"].pcreregs, 1)
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ package router
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
"github.com/unistack-org/micro/v3/api"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Router is used to determine an endpoint for a request
|
// Router is used to determine an endpoint for a request
|
||||||
|
|||||||
@@ -1,245 +0,0 @@
|
|||||||
package router_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler/rpc"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
rregistry "github.com/micro/go-micro/v3/api/router/registry"
|
|
||||||
rstatic "github.com/micro/go-micro/v3/api/router/static"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
gcli "github.com/micro/go-micro/v3/client/grpc"
|
|
||||||
rmemory "github.com/micro/go-micro/v3/registry/memory"
|
|
||||||
"github.com/micro/go-micro/v3/server"
|
|
||||||
gsrv "github.com/micro/go-micro/v3/server/grpc"
|
|
||||||
pb "github.com/micro/go-micro/v3/server/grpc/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
// server is used to implement helloworld.GreeterServer.
|
|
||||||
type testServer struct {
|
|
||||||
msgCount int
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) CallPcre(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) CallPcreInvalid(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initial(t *testing.T) (server.Server, client.Client) {
|
|
||||||
r := rmemory.NewRegistry()
|
|
||||||
|
|
||||||
// create a new client
|
|
||||||
s := gsrv.NewServer(
|
|
||||||
server.Name("foo"),
|
|
||||||
server.Registry(r),
|
|
||||||
)
|
|
||||||
|
|
||||||
// create a new server
|
|
||||||
c := gcli.NewClient(
|
|
||||||
client.Registry(r),
|
|
||||||
)
|
|
||||||
|
|
||||||
h := &testServer{}
|
|
||||||
pb.RegisterTestHandler(s, h)
|
|
||||||
|
|
||||||
if err := s.Start(); err != nil {
|
|
||||||
t.Fatalf("failed to start: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return s, c
|
|
||||||
}
|
|
||||||
|
|
||||||
func check(t *testing.T, addr string, path string, expected string) {
|
|
||||||
req, err := http.NewRequest("POST", fmt.Sprintf(path, addr), nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rsp, err := (&http.Client{}).Do(req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
defer rsp.Body.Close()
|
|
||||||
|
|
||||||
buf, err := ioutil.ReadAll(rsp.Body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonMsg := expected
|
|
||||||
if string(buf) != jsonMsg {
|
|
||||||
t.Fatalf("invalid message received, parsing error %s != %s", buf, jsonMsg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterRegistryPcre(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rregistry.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
|
|
||||||
defer hsrv.Close()
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call/TEST", `{"msg":"Hello TEST"}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticPcre(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
err := router.Register(&api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"^/api/v0/test/call/?$"},
|
|
||||||
Handler: "rpc",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
defer hsrv.Close()
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call", `{"msg":"Hello "}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticGpath(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
err := router.Register(&api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"/api/v0/test/call/{uuid}"},
|
|
||||||
Handler: "rpc",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
defer hsrv.Close()
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call/TEST", `{"msg":"Hello TEST"}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticPcreInvalid(t *testing.T) {
|
|
||||||
var ep *api.Endpoint
|
|
||||||
var err error
|
|
||||||
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
ep = &api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"^/api/v0/test/call/?"},
|
|
||||||
Handler: "rpc",
|
|
||||||
}
|
|
||||||
|
|
||||||
err = router.Register(ep)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("invalid endpoint %v", ep)
|
|
||||||
}
|
|
||||||
|
|
||||||
ep = &api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"/api/v0/test/call/?$"},
|
|
||||||
Handler: "rpc",
|
|
||||||
}
|
|
||||||
|
|
||||||
err = router.Register(ep)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("invalid endpoint %v", ep)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = c
|
|
||||||
}
|
|
||||||
@@ -1,356 +0,0 @@
|
|||||||
package static
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
"github.com/micro/go-micro/v3/api/router/util"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
rutil "github.com/micro/go-micro/v3/util/registry"
|
|
||||||
)
|
|
||||||
|
|
||||||
type endpoint struct {
|
|
||||||
apiep *api.Endpoint
|
|
||||||
hostregs []*regexp.Regexp
|
|
||||||
pathregs []util.Pattern
|
|
||||||
pcreregs []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
// router is the default router
|
|
||||||
type staticRouter struct {
|
|
||||||
exit chan bool
|
|
||||||
opts router.Options
|
|
||||||
sync.RWMutex
|
|
||||||
eps map[string]*endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) isClosed() bool {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
// watch for endpoint changes
|
|
||||||
func (r *staticRouter) watch() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
if r.isClosed() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for changes
|
|
||||||
w, err := r.opts.Registry.Watch()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
log.Println("Error watching endpoints", err)
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan bool)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-ch:
|
|
||||||
w.Stop()
|
|
||||||
case <-r.exit:
|
|
||||||
w.Stop()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// reset if we get here
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
for {
|
|
||||||
// process next event
|
|
||||||
res, err := w.Next()
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Error getting next endpoint", err)
|
|
||||||
close(ch)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
r.process(res)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
func (r *staticRouter) Register(ep *api.Endpoint) error {
|
|
||||||
if err := api.Validate(ep); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var pathregs []util.Pattern
|
|
||||||
var hostregs []*regexp.Regexp
|
|
||||||
var pcreregs []*regexp.Regexp
|
|
||||||
|
|
||||||
for _, h := range ep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
hostreg, err := regexp.CompilePOSIX(h)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
hostregs = append(hostregs, hostreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range ep.Path {
|
|
||||||
var pcreok bool
|
|
||||||
|
|
||||||
// pcre only when we have start and end markers
|
|
||||||
if p[0] == '^' && p[len(p)-1] == '$' {
|
|
||||||
pcrereg, err := regexp.CompilePOSIX(p)
|
|
||||||
if err == nil {
|
|
||||||
pcreregs = append(pcreregs, pcrereg)
|
|
||||||
pcreok = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rule, err := util.Parse(p)
|
|
||||||
if err != nil && !pcreok {
|
|
||||||
return err
|
|
||||||
} else if err != nil && pcreok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
tpl := rule.Compile()
|
|
||||||
pathreg, err := util.NewPattern(tpl.Version, tpl.OpCodes, tpl.Pool, "")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
pathregs = append(pathregs, pathreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Lock()
|
|
||||||
r.eps[ep.Name] = &endpoint{
|
|
||||||
apiep: ep,
|
|
||||||
pcreregs: pcreregs,
|
|
||||||
pathregs: pathregs,
|
|
||||||
hostregs: hostregs,
|
|
||||||
}
|
|
||||||
r.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Deregister(ep *api.Endpoint) error {
|
|
||||||
if err := api.Validate(ep); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.Lock()
|
|
||||||
delete(r.eps, ep.Name)
|
|
||||||
r.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Options() router.Options {
|
|
||||||
return r.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Close() error {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(r.exit)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Endpoint(req *http.Request) (*api.Service, error) {
|
|
||||||
ep, err := r.endpoint(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
epf := strings.Split(ep.apiep.Name, ".")
|
|
||||||
services, err := r.opts.Registry.GetService(epf[0])
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// hack for stream endpoint
|
|
||||||
if ep.apiep.Stream {
|
|
||||||
svcs := rutil.Copy(services)
|
|
||||||
for _, svc := range svcs {
|
|
||||||
if len(svc.Endpoints) == 0 {
|
|
||||||
e := ®istry.Endpoint{}
|
|
||||||
e.Name = strings.Join(epf[1:], ".")
|
|
||||||
e.Metadata = make(map[string]string)
|
|
||||||
e.Metadata["stream"] = "true"
|
|
||||||
svc.Endpoints = append(svc.Endpoints, e)
|
|
||||||
}
|
|
||||||
for _, e := range svc.Endpoints {
|
|
||||||
e.Name = strings.Join(epf[1:], ".")
|
|
||||||
e.Metadata = make(map[string]string)
|
|
||||||
e.Metadata["stream"] = "true"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
services = svcs
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := &api.Service{
|
|
||||||
Name: epf[0],
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: strings.Join(epf[1:], "."),
|
|
||||||
Handler: "rpc",
|
|
||||||
Host: ep.apiep.Host,
|
|
||||||
Method: ep.apiep.Method,
|
|
||||||
Path: ep.apiep.Path,
|
|
||||||
Body: ep.apiep.Body,
|
|
||||||
Stream: ep.apiep.Stream,
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}
|
|
||||||
|
|
||||||
return svc, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) endpoint(req *http.Request) (*endpoint, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.RLock()
|
|
||||||
defer r.RUnlock()
|
|
||||||
|
|
||||||
var idx int
|
|
||||||
if len(req.URL.Path) > 0 && req.URL.Path != "/" {
|
|
||||||
idx = 1
|
|
||||||
}
|
|
||||||
path := strings.Split(req.URL.Path[idx:], "/")
|
|
||||||
// use the first match
|
|
||||||
// TODO: weighted matching
|
|
||||||
|
|
||||||
for _, ep := range r.eps {
|
|
||||||
var mMatch, hMatch, pMatch bool
|
|
||||||
|
|
||||||
// 1. try method
|
|
||||||
for _, m := range ep.apiep.Method {
|
|
||||||
if m == req.Method {
|
|
||||||
mMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !mMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api method match %s", req.Method)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. try host
|
|
||||||
if len(ep.apiep.Host) == 0 {
|
|
||||||
hMatch = true
|
|
||||||
} else {
|
|
||||||
for idx, h := range ep.apiep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if ep.hostregs[idx].MatchString(req.URL.Host) {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api host match %s", req.URL.Host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. try google.api path
|
|
||||||
for _, pathreg := range ep.pathregs {
|
|
||||||
matches, err := pathreg.Match(path, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath match %s = %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
ctx := req.Context()
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(metadata.Metadata)
|
|
||||||
}
|
|
||||||
for k, v := range matches {
|
|
||||||
md[fmt.Sprintf("x-api-field-%s", k)] = v
|
|
||||||
}
|
|
||||||
md["x-api-body"] = ep.apiep.Body
|
|
||||||
*req = *req.Clone(metadata.NewContext(ctx, md))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
// 4. try path via pcre path matching
|
|
||||||
for _, pathreg := range ep.pcreregs {
|
|
||||||
if !pathreg.MatchString(req.URL.Path) {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path not match %s != %v", req.URL.Path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// TODO: Percentage traffic
|
|
||||||
|
|
||||||
// we got here, so its a match
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// no match
|
|
||||||
return nil, fmt.Errorf("endpoint not found for %v", req.URL)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Route(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get an endpoint
|
|
||||||
ep, err := r.Endpoint(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRouter(opts ...router.Option) *staticRouter {
|
|
||||||
options := router.NewOptions(opts...)
|
|
||||||
r := &staticRouter{
|
|
||||||
exit: make(chan bool),
|
|
||||||
opts: options,
|
|
||||||
eps: make(map[string]*endpoint),
|
|
||||||
}
|
|
||||||
//go r.watch()
|
|
||||||
//go r.refresh()
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
@@ -15,6 +15,7 @@ var (
|
|||||||
|
|
||||||
// Provider is a ACME provider interface
|
// Provider is a ACME provider interface
|
||||||
type Provider interface {
|
type Provider interface {
|
||||||
|
Init(...Option) error
|
||||||
// Listen returns a new listener
|
// Listen returns a new listener
|
||||||
Listen(...string) (net.Listener, error)
|
Listen(...string) (net.Listener, error)
|
||||||
// TLSConfig returns a tls config
|
// TLSConfig returns a tls config
|
||||||
|
|||||||
@@ -7,14 +7,18 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
"github.com/unistack-org/micro/v3/api/server/acme"
|
||||||
"github.com/micro/go-micro/v3/logger"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
"golang.org/x/crypto/acme/autocert"
|
"golang.org/x/crypto/acme/autocert"
|
||||||
)
|
)
|
||||||
|
|
||||||
// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert
|
// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert
|
||||||
type autocertProvider struct{}
|
type autocertProvider struct{}
|
||||||
|
|
||||||
|
func (a *autocertProvider) Init(opts ...acme.Option) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Listen implements acme.Provider
|
// Listen implements acme.Provider
|
||||||
func (a *autocertProvider) Listen(hosts ...string) (net.Listener, error) {
|
func (a *autocertProvider) Listen(hosts ...string) (net.Listener, error) {
|
||||||
return autocert.NewListener(hosts...), nil
|
return autocert.NewListener(hosts...), nil
|
||||||
@@ -31,8 +35,8 @@ func (a *autocertProvider) TLSConfig(hosts ...string) (*tls.Config, error) {
|
|||||||
}
|
}
|
||||||
dir := cacheDir()
|
dir := cacheDir()
|
||||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
|
if logger.V(logger.InfoLevel) {
|
||||||
logger.Infof("warning: autocert not using a cache: %v", err)
|
logger.Info("warning: autocert not using a cache: %v", err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
m.Cache = autocert.DirCache(dir)
|
m.Cache = autocert.DirCache(dir)
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ package certmagic
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/caddyserver/certmagic"
|
"github.com/caddyserver/certmagic"
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
"github.com/unistack-org/micro/v3/api/server/acme"
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type certmagicProvider struct {
|
type certmagicProvider struct {
|
||||||
@@ -48,6 +48,15 @@ func (c *certmagicProvider) TLSConfig(hosts ...string) (*tls.Config, error) {
|
|||||||
return certmagic.TLS(hosts)
|
return certmagic.TLS(hosts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *certmagicProvider) Init(opts ...acme.Option) error {
|
||||||
|
if p.opts.Cache != nil {
|
||||||
|
if _, ok := p.opts.Cache.(certmagic.Storage); !ok {
|
||||||
|
return fmt.Errorf("ACME: cache provided doesn't implement certmagic's Storage interface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// NewProvider returns a certmagic provider
|
// NewProvider returns a certmagic provider
|
||||||
func NewProvider(options ...acme.Option) acme.Provider {
|
func NewProvider(options ...acme.Option) acme.Provider {
|
||||||
opts := acme.DefaultOptions()
|
opts := acme.DefaultOptions()
|
||||||
@@ -56,12 +65,6 @@ func NewProvider(options ...acme.Option) acme.Provider {
|
|||||||
o(&opts)
|
o(&opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Cache != nil {
|
|
||||||
if _, ok := opts.Cache.(certmagic.Storage); !ok {
|
|
||||||
logger.Fatal("ACME: cache provided doesn't implement certmagic's Storage interface")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &certmagicProvider{
|
return &certmagicProvider{
|
||||||
opts: opts,
|
opts: opts,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/caddyserver/certmagic"
|
"github.com/caddyserver/certmagic"
|
||||||
"github.com/micro/go-micro/v3/store"
|
"github.com/unistack-org/micro/v3/store"
|
||||||
"github.com/micro/go-micro/v3/sync"
|
"github.com/unistack-org/micro/v3/sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// File represents a "File" that will be stored in store.Store - the contents and last modified time
|
// File represents a "File" that will be stored in store.Store - the contents and last modified time
|
||||||
@@ -52,14 +52,14 @@ func (s *storage) Store(key string, value []byte) error {
|
|||||||
Key: key,
|
Key: key,
|
||||||
Value: buf.Bytes(),
|
Value: buf.Bytes(),
|
||||||
}
|
}
|
||||||
return s.store.Write(r)
|
return s.store.Write(s.store.Options().Context, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *storage) Load(key string) ([]byte, error) {
|
func (s *storage) Load(key string) ([]byte, error) {
|
||||||
if !s.Exists(key) {
|
if !s.Exists(key) {
|
||||||
return nil, certmagic.ErrNotExist(errors.New(key + " doesn't exist"))
|
return nil, certmagic.ErrNotExist(errors.New(key + " doesn't exist"))
|
||||||
}
|
}
|
||||||
records, err := s.store.Read(key)
|
records, err := s.store.Read(s.store.Options().Context, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -77,18 +77,18 @@ func (s *storage) Load(key string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *storage) Delete(key string) error {
|
func (s *storage) Delete(key string) error {
|
||||||
return s.store.Delete(key)
|
return s.store.Delete(s.store.Options().Context, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *storage) Exists(key string) bool {
|
func (s *storage) Exists(key string) bool {
|
||||||
if _, err := s.store.Read(key); err != nil {
|
if _, err := s.store.Read(s.store.Options().Context, key); err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *storage) List(prefix string, recursive bool) ([]string, error) {
|
func (s *storage) List(prefix string, recursive bool) ([]string, error) {
|
||||||
keys, err := s.store.List()
|
keys, err := s.store.List(s.store.Options().Context)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -116,7 +116,7 @@ func (s *storage) List(prefix string, recursive bool) ([]string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *storage) Stat(key string) (certmagic.KeyInfo, error) {
|
func (s *storage) Stat(key string) (certmagic.KeyInfo, error) {
|
||||||
records, err := s.store.Read(key)
|
records, err := s.store.Read(s.store.Options().Context, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return certmagic.KeyInfo{}, err
|
return certmagic.KeyInfo{}, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ func OnDemand(b bool) Option {
|
|||||||
|
|
||||||
// Cache provides a cache / storage interface to the underlying ACME library
|
// Cache provides a cache / storage interface to the underlying ACME library
|
||||||
// as there is no standard, this needs to be validated by the underlying
|
// as there is no standard, this needs to be validated by the underlying
|
||||||
// implentation.
|
// implementation
|
||||||
func Cache(c interface{}) Option {
|
func Cache(c interface{}) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Cache = c
|
o.Cache = c
|
||||||
|
|||||||
@@ -5,32 +5,24 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
"github.com/unistack-org/micro/v3/api/server"
|
||||||
"github.com/micro/go-micro/v3/api/server"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
"github.com/micro/go-micro/v3/api/server/cors"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type httpServer struct {
|
type httpServer struct {
|
||||||
mux *http.ServeMux
|
mux *http.ServeMux
|
||||||
opts server.Options
|
opts server.Options
|
||||||
|
|
||||||
mtx sync.RWMutex
|
sync.RWMutex
|
||||||
address string
|
address string
|
||||||
exit chan chan error
|
exit chan chan error
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(address string, opts ...server.Option) server.Server {
|
func NewServer(address string, opts ...server.Option) server.Server {
|
||||||
var options server.Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &httpServer{
|
return &httpServer{
|
||||||
opts: options,
|
opts: server.NewOptions(opts...),
|
||||||
mux: http.NewServeMux(),
|
mux: http.NewServeMux(),
|
||||||
address: address,
|
address: address,
|
||||||
exit: make(chan chan error),
|
exit: make(chan chan error),
|
||||||
@@ -38,8 +30,8 @@ func NewServer(address string, opts ...server.Option) server.Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *httpServer) Address() string {
|
func (s *httpServer) Address() string {
|
||||||
s.mtx.RLock()
|
s.RLock()
|
||||||
defer s.mtx.RUnlock()
|
defer s.RUnlock()
|
||||||
return s.address
|
return s.address
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,14 +50,6 @@ func (s *httpServer) Handle(path string, handler http.Handler) {
|
|||||||
handler = wrapper(handler)
|
handler = wrapper(handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrap with cors
|
|
||||||
if s.opts.EnableCORS {
|
|
||||||
handler = cors.CombinedCORSHandler(handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
// wrap with logger
|
|
||||||
handler = handlers.CombinedLoggingHandler(os.Stdout, handler)
|
|
||||||
|
|
||||||
s.mux.Handle(path, handler)
|
s.mux.Handle(path, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,6 +57,9 @@ func (s *httpServer) Start() error {
|
|||||||
var l net.Listener
|
var l net.Listener
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
s.RLock()
|
||||||
|
config := s.opts
|
||||||
|
s.RUnlock()
|
||||||
if s.opts.EnableACME && s.opts.ACMEProvider != nil {
|
if s.opts.EnableACME && s.opts.ACMEProvider != nil {
|
||||||
// should we check the address to make sure its using :443?
|
// should we check the address to make sure its using :443?
|
||||||
l, err = s.opts.ACMEProvider.Listen(s.opts.ACMEHosts...)
|
l, err = s.opts.ACMEProvider.Listen(s.opts.ACMEHosts...)
|
||||||
@@ -86,18 +73,21 @@ func (s *httpServer) Start() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
|
if config.Logger.V(logger.InfoLevel) {
|
||||||
logger.Infof("HTTP API Listening on %s", l.Addr().String())
|
config.Logger.Info("HTTP API Listening on %s", l.Addr().String())
|
||||||
}
|
}
|
||||||
|
|
||||||
s.mtx.Lock()
|
s.Lock()
|
||||||
s.address = l.Addr().String()
|
s.address = l.Addr().String()
|
||||||
s.mtx.Unlock()
|
s.Unlock()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
if err := http.Serve(l, s.mux); err != nil {
|
if err := http.Serve(l, s.mux); err != nil {
|
||||||
// temporary fix
|
// temporary fix
|
||||||
//logger.Fatal(err)
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
|
config.Logger.Error("serve err: %v", err)
|
||||||
|
}
|
||||||
|
s.Stop()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,15 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
"github.com/unistack-org/micro/v3/api/resolver"
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
"github.com/unistack-org/micro/v3/api/server/acme"
|
||||||
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Option func
|
||||||
type Option func(o *Options)
|
type Option func(o *Options)
|
||||||
|
|
||||||
|
// Options for api server
|
||||||
type Options struct {
|
type Options struct {
|
||||||
EnableACME bool
|
EnableACME bool
|
||||||
EnableCORS bool
|
EnableCORS bool
|
||||||
@@ -19,13 +22,25 @@ type Options struct {
|
|||||||
TLSConfig *tls.Config
|
TLSConfig *tls.Config
|
||||||
Resolver resolver.Resolver
|
Resolver resolver.Resolver
|
||||||
Wrappers []Wrapper
|
Wrappers []Wrapper
|
||||||
|
Logger logger.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptions returns new Options
|
||||||
|
func NewOptions(opts ...Option) Options {
|
||||||
|
options := Options{
|
||||||
|
Logger: logger.DefaultLogger,
|
||||||
|
}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&options)
|
||||||
|
}
|
||||||
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
type Wrapper func(h http.Handler) http.Handler
|
type Wrapper func(h http.Handler) http.Handler
|
||||||
|
|
||||||
func WrapHandler(w Wrapper) Option {
|
func WrapHandler(w ...Wrapper) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Wrappers = append(o.Wrappers, w)
|
o.Wrappers = append(o.Wrappers, w...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,3 +85,9 @@ func Resolver(r resolver.Resolver) Option {
|
|||||||
o.Resolver = r
|
o.Resolver = r
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Logger(l logger.Logger) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
o.Logger = l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,268 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// source: api/service/proto/api.proto
|
|
||||||
|
|
||||||
package go_micro_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
grpc "google.golang.org/grpc"
|
|
||||||
codes "google.golang.org/grpc/codes"
|
|
||||||
status "google.golang.org/grpc/status"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
type Endpoint struct {
|
|
||||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
|
||||||
Host []string `protobuf:"bytes,2,rep,name=host,proto3" json:"host,omitempty"`
|
|
||||||
Path []string `protobuf:"bytes,3,rep,name=path,proto3" json:"path,omitempty"`
|
|
||||||
Method []string `protobuf:"bytes,4,rep,name=method,proto3" json:"method,omitempty"`
|
|
||||||
Stream bool `protobuf:"varint,5,opt,name=stream,proto3" json:"stream,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) Reset() { *m = Endpoint{} }
|
|
||||||
func (m *Endpoint) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Endpoint) ProtoMessage() {}
|
|
||||||
func (*Endpoint) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_c4a48b6b680b5c31, []int{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Endpoint.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Endpoint.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Endpoint.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Endpoint.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Endpoint.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Endpoint proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Endpoint) GetName() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Name
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetHost() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Host
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetPath() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Path
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetMethod() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Method
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetStream() bool {
|
|
||||||
if m != nil {
|
|
||||||
return m.Stream
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type EmptyResponse struct {
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *EmptyResponse) Reset() { *m = EmptyResponse{} }
|
|
||||||
func (m *EmptyResponse) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*EmptyResponse) ProtoMessage() {}
|
|
||||||
func (*EmptyResponse) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_c4a48b6b680b5c31, []int{1}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *EmptyResponse) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_EmptyResponse.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Size(m)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_EmptyResponse.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_EmptyResponse proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
proto.RegisterType((*Endpoint)(nil), "go.micro.api.Endpoint")
|
|
||||||
proto.RegisterType((*EmptyResponse)(nil), "go.micro.api.EmptyResponse")
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() { proto.RegisterFile("api/service/proto/api.proto", fileDescriptor_c4a48b6b680b5c31) }
|
|
||||||
|
|
||||||
var fileDescriptor_c4a48b6b680b5c31 = []byte{
|
|
||||||
// 212 bytes of a gzipped FileDescriptorProto
|
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0xd0, 0xc1, 0x4a, 0x03, 0x31,
|
|
||||||
0x10, 0x80, 0x61, 0xd7, 0xad, 0x65, 0x1d, 0x14, 0x21, 0x87, 0x12, 0xec, 0x65, 0xd9, 0x53, 0x4f,
|
|
||||||
0x59, 0xd0, 0x27, 0x28, 0xda, 0x17, 0xd8, 0x37, 0x88, 0xed, 0xd0, 0x9d, 0x43, 0x32, 0x43, 0x32,
|
|
||||||
0x14, 0x7c, 0x08, 0xdf, 0x59, 0x12, 0x2b, 0x2c, 0x5e, 0xbd, 0xfd, 0xf3, 0x1d, 0x86, 0x61, 0x60,
|
|
||||||
0xeb, 0x85, 0xc6, 0x8c, 0xe9, 0x42, 0x47, 0x1c, 0x25, 0xb1, 0xf2, 0xe8, 0x85, 0x5c, 0x2d, 0xf3,
|
|
||||||
0x70, 0x66, 0x17, 0xe8, 0x98, 0xd8, 0x79, 0xa1, 0xe1, 0x02, 0xdd, 0x21, 0x9e, 0x84, 0x29, 0xaa,
|
|
||||||
0x31, 0xb0, 0x8a, 0x3e, 0xa0, 0x6d, 0xfa, 0x66, 0x77, 0x3f, 0xd5, 0x2e, 0x36, 0x73, 0x56, 0x7b,
|
|
||||||
0xdb, 0xb7, 0xc5, 0x4a, 0x17, 0x13, 0xaf, 0xb3, 0x6d, 0x7f, 0xac, 0xb4, 0xd9, 0xc0, 0x3a, 0xa0,
|
|
||||||
0xce, 0x7c, 0xb2, 0xab, 0xaa, 0xd7, 0xa9, 0x78, 0xd6, 0x84, 0x3e, 0xd8, 0xbb, 0xbe, 0xd9, 0x75,
|
|
||||||
0xd3, 0x75, 0x1a, 0x9e, 0xe0, 0xf1, 0x10, 0x44, 0x3f, 0x27, 0xcc, 0xc2, 0x31, 0xe3, 0xcb, 0x57,
|
|
||||||
0x03, 0xed, 0x5e, 0xc8, 0xec, 0xa1, 0x9b, 0xf0, 0x4c, 0x59, 0x31, 0x99, 0x8d, 0x5b, 0xde, 0xea,
|
|
||||||
0x7e, 0x0f, 0x7d, 0xde, 0xfe, 0xf1, 0xe5, 0xa2, 0xe1, 0xc6, 0xbc, 0x01, 0xbc, 0x63, 0xfa, 0xdf,
|
|
||||||
0x92, 0x8f, 0x75, 0xfd, 0xd6, 0xeb, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0x46, 0x62, 0x67, 0x30,
|
|
||||||
0x4c, 0x01, 0x00, 0x00,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ context.Context
|
|
||||||
var _ grpc.ClientConn
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the grpc package it is being compiled against.
|
|
||||||
const _ = grpc.SupportPackageIsVersion4
|
|
||||||
|
|
||||||
// ApiClient is the client API for Api service.
|
|
||||||
//
|
|
||||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
|
|
||||||
type ApiClient interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error)
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiClient struct {
|
|
||||||
cc *grpc.ClientConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewApiClient(cc *grpc.ClientConn) ApiClient {
|
|
||||||
return &apiClient{cc}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiClient) Register(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error) {
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.api.Api/Register", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiClient) Deregister(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error) {
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.api.Api/Deregister", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApiServer is the server API for Api service.
|
|
||||||
type ApiServer interface {
|
|
||||||
Register(context.Context, *Endpoint) (*EmptyResponse, error)
|
|
||||||
Deregister(context.Context, *Endpoint) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnimplementedApiServer can be embedded to have forward compatible implementations.
|
|
||||||
type UnimplementedApiServer struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*UnimplementedApiServer) Register(ctx context.Context, req *Endpoint) (*EmptyResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Register not implemented")
|
|
||||||
}
|
|
||||||
func (*UnimplementedApiServer) Deregister(ctx context.Context, req *Endpoint) (*EmptyResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Deregister not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterApiServer(s *grpc.Server, srv ApiServer) {
|
|
||||||
s.RegisterService(&_Api_serviceDesc, srv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Api_Register_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(Endpoint)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(ApiServer).Register(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.api.Api/Register",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(ApiServer).Register(ctx, req.(*Endpoint))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Api_Deregister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(Endpoint)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(ApiServer).Deregister(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.api.Api/Deregister",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(ApiServer).Deregister(ctx, req.(*Endpoint))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
var _Api_serviceDesc = grpc.ServiceDesc{
|
|
||||||
ServiceName: "go.micro.api.Api",
|
|
||||||
HandlerType: (*ApiServer)(nil),
|
|
||||||
Methods: []grpc.MethodDesc{
|
|
||||||
{
|
|
||||||
MethodName: "Register",
|
|
||||||
Handler: _Api_Register_Handler,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
MethodName: "Deregister",
|
|
||||||
Handler: _Api_Deregister_Handler,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Streams: []grpc.StreamDesc{},
|
|
||||||
Metadata: "api/service/proto/api.proto",
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
|
||||||
// source: api/service/proto/api.proto
|
|
||||||
|
|
||||||
package go_micro_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
api "github.com/micro/go-micro/v3/api"
|
|
||||||
client "github.com/micro/go-micro/v3/client"
|
|
||||||
server "github.com/micro/go-micro/v3/server"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ api.Endpoint
|
|
||||||
var _ context.Context
|
|
||||||
var _ client.Option
|
|
||||||
var _ server.Option
|
|
||||||
|
|
||||||
// Api Endpoints for Api service
|
|
||||||
|
|
||||||
func NewApiEndpoints() []*api.Endpoint {
|
|
||||||
return []*api.Endpoint{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client API for Api service
|
|
||||||
|
|
||||||
type ApiService interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error)
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiService struct {
|
|
||||||
c client.Client
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewApiService(name string, c client.Client) ApiService {
|
|
||||||
return &apiService{
|
|
||||||
c: c,
|
|
||||||
name: name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiService) Register(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Api.Register", in)
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiService) Deregister(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Api.Deregister", in)
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server API for Api service
|
|
||||||
|
|
||||||
type ApiHandler interface {
|
|
||||||
Register(context.Context, *Endpoint, *EmptyResponse) error
|
|
||||||
Deregister(context.Context, *Endpoint, *EmptyResponse) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterApiHandler(s server.Server, hdlr ApiHandler, opts ...server.HandlerOption) error {
|
|
||||||
type api interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, out *EmptyResponse) error
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, out *EmptyResponse) error
|
|
||||||
}
|
|
||||||
type Api struct {
|
|
||||||
api
|
|
||||||
}
|
|
||||||
h := &apiHandler{hdlr}
|
|
||||||
return s.Handle(s.NewHandler(&Api{h}, opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiHandler struct {
|
|
||||||
ApiHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *apiHandler) Register(ctx context.Context, in *Endpoint, out *EmptyResponse) error {
|
|
||||||
return h.ApiHandler.Register(ctx, in, out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *apiHandler) Deregister(ctx context.Context, in *Endpoint, out *EmptyResponse) error {
|
|
||||||
return h.ApiHandler.Deregister(ctx, in, out)
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package go.micro.api;
|
|
||||||
|
|
||||||
service Api {
|
|
||||||
rpc Register(Endpoint) returns (EmptyResponse) {};
|
|
||||||
rpc Deregister(Endpoint) returns (EmptyResponse) {};
|
|
||||||
}
|
|
||||||
|
|
||||||
message Endpoint {
|
|
||||||
string name = 1;
|
|
||||||
repeated string host = 2;
|
|
||||||
repeated string path = 3;
|
|
||||||
repeated string method = 4;
|
|
||||||
bool stream = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EmptyResponse {}
|
|
||||||
@@ -17,6 +17,7 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
DefaultAuth Auth = &NoopAuth{opts: NewOptions()}
|
||||||
// ErrInvalidToken is when the token provided is not valid
|
// ErrInvalidToken is when the token provided is not valid
|
||||||
ErrInvalidToken = errors.New("invalid token provided")
|
ErrInvalidToken = errors.New("invalid token provided")
|
||||||
// ErrForbidden is when a user does not have the necessary scope to access a resource
|
// ErrForbidden is when a user does not have the necessary scope to access a resource
|
||||||
|
|||||||
151
auth/jwt/jwt.go
151
auth/jwt/jwt.go
@@ -1,151 +0,0 @@
|
|||||||
// Package jwt is a jwt implementation of the auth interface
|
|
||||||
package jwt
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/auth"
|
|
||||||
"github.com/micro/go-micro/v3/util/token"
|
|
||||||
"github.com/micro/go-micro/v3/util/token/jwt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewAuth returns a new instance of the Auth service
|
|
||||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
|
||||||
j := new(jwtAuth)
|
|
||||||
j.Init(opts...)
|
|
||||||
return j
|
|
||||||
}
|
|
||||||
|
|
||||||
type jwtAuth struct {
|
|
||||||
options auth.Options
|
|
||||||
token token.Provider
|
|
||||||
rules []*auth.Rule
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) String() string {
|
|
||||||
return "jwt"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Init(opts ...auth.Option) {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&j.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
j.token = jwt.NewTokenProvider(
|
|
||||||
token.WithPrivateKey(j.options.PrivateKey),
|
|
||||||
token.WithPublicKey(j.options.PublicKey),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Options() auth.Options {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
return j.options
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) {
|
|
||||||
options := auth.NewGenerateOptions(opts...)
|
|
||||||
if len(options.Issuer) == 0 {
|
|
||||||
options.Issuer = j.Options().Issuer
|
|
||||||
}
|
|
||||||
|
|
||||||
account := &auth.Account{
|
|
||||||
ID: id,
|
|
||||||
Type: options.Type,
|
|
||||||
Scopes: options.Scopes,
|
|
||||||
Metadata: options.Metadata,
|
|
||||||
Issuer: options.Issuer,
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate a JWT secret which can be provided to the Token() method
|
|
||||||
// and exchanged for an access token
|
|
||||||
secret, err := j.token.Generate(account, token.WithExpiry(time.Hour*24*365))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
account.Secret = secret.Token
|
|
||||||
|
|
||||||
// return the account
|
|
||||||
return account, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Grant(rule *auth.Rule) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
j.rules = append(j.rules, rule)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Revoke(rule *auth.Rule) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
rules := []*auth.Rule{}
|
|
||||||
for _, r := range j.rules {
|
|
||||||
if r.ID != rule.ID {
|
|
||||||
rules = append(rules, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
j.rules = rules
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
var options auth.VerifyOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return auth.VerifyAccess(j.rules, acc, res)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
return j.rules, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Inspect(token string) (*auth.Account, error) {
|
|
||||||
return j.token.Inspect(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Token(opts ...auth.TokenOption) (*auth.Token, error) {
|
|
||||||
options := auth.NewTokenOptions(opts...)
|
|
||||||
|
|
||||||
secret := options.RefreshToken
|
|
||||||
if len(options.Secret) > 0 {
|
|
||||||
secret = options.Secret
|
|
||||||
}
|
|
||||||
|
|
||||||
account, err := j.token.Inspect(secret)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
access, err := j.token.Generate(account, token.WithExpiry(options.Expiry))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
refresh, err := j.token.Generate(account, token.WithExpiry(options.Expiry+time.Hour))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &auth.Token{
|
|
||||||
Created: access.Created,
|
|
||||||
Expiry: access.Expiry,
|
|
||||||
AccessToken: access.Token,
|
|
||||||
RefreshToken: refresh.Token,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
73
auth/noop.go
Normal file
73
auth/noop.go
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type NoopAuth struct {
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns the name of the implementation
|
||||||
|
func (n *NoopAuth) String() string {
|
||||||
|
return "noop"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init the auth
|
||||||
|
func (n *NoopAuth) Init(opts ...Option) {
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&n.opts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options set for auth
|
||||||
|
func (n *NoopAuth) Options() Options {
|
||||||
|
return n.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a new account
|
||||||
|
func (n *NoopAuth) Generate(id string, opts ...GenerateOption) (*Account, error) {
|
||||||
|
options := NewGenerateOptions(opts...)
|
||||||
|
|
||||||
|
return &Account{
|
||||||
|
ID: id,
|
||||||
|
Secret: options.Secret,
|
||||||
|
Metadata: options.Metadata,
|
||||||
|
Scopes: options.Scopes,
|
||||||
|
Issuer: n.Options().Issuer,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grant access to a resource
|
||||||
|
func (n *NoopAuth) Grant(rule *Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke access to a resource
|
||||||
|
func (n *NoopAuth) Revoke(rule *Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rules used to verify requests
|
||||||
|
func (n *NoopAuth) Rules(opts ...RulesOption) ([]*Rule, error) {
|
||||||
|
return []*Rule{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify an account has access to a resource
|
||||||
|
func (n *NoopAuth) Verify(acc *Account, res *Resource, opts ...VerifyOption) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inspect a token
|
||||||
|
func (n *NoopAuth) Inspect(token string) (*Account, error) {
|
||||||
|
uid, err := uuid.NewRandom()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Account{ID: uid.String(), Issuer: n.Options().Issuer}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token generation using an account id and secret
|
||||||
|
func (n *NoopAuth) Token(opts ...TokenOption) (*Token, error) {
|
||||||
|
return &Token{}, nil
|
||||||
|
}
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package noop
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
|
||||||
var options auth.Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &noop{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type noop struct {
|
|
||||||
opts auth.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
// String returns the name of the implementation
|
|
||||||
func (n *noop) String() string {
|
|
||||||
return "noop"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Init the auth
|
|
||||||
func (n *noop) Init(opts ...auth.Option) {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&n.opts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Options set for auth
|
|
||||||
func (n *noop) Options() auth.Options {
|
|
||||||
return n.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate a new account
|
|
||||||
func (n *noop) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) {
|
|
||||||
options := auth.NewGenerateOptions(opts...)
|
|
||||||
|
|
||||||
return &auth.Account{
|
|
||||||
ID: id,
|
|
||||||
Secret: options.Secret,
|
|
||||||
Metadata: options.Metadata,
|
|
||||||
Scopes: options.Scopes,
|
|
||||||
Issuer: n.Options().Issuer,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Grant access to a resource
|
|
||||||
func (n *noop) Grant(rule *auth.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Revoke access to a resource
|
|
||||||
func (n *noop) Revoke(rule *auth.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rules used to verify requests
|
|
||||||
func (n *noop) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) {
|
|
||||||
return []*auth.Rule{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify an account has access to a resource
|
|
||||||
func (n *noop) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inspect a token
|
|
||||||
func (n *noop) Inspect(token string) (*auth.Account, error) {
|
|
||||||
return &auth.Account{ID: uuid.New().String(), Issuer: n.Options().Issuer}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Token generation using an account id and secret
|
|
||||||
func (n *noop) Token(opts ...auth.TokenOption) (*auth.Token, error) {
|
|
||||||
return &auth.Token{}, nil
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/store"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
|
"github.com/unistack-org/micro/v3/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewOptions(opts ...Option) Options {
|
func NewOptions(opts ...Option) Options {
|
||||||
@@ -34,6 +35,8 @@ type Options struct {
|
|||||||
Store store.Store
|
Store store.Store
|
||||||
// Addrs sets the addresses of auth
|
// Addrs sets the addresses of auth
|
||||||
Addrs []string
|
Addrs []string
|
||||||
|
// Logger sets the logger
|
||||||
|
Logger logger.Logger
|
||||||
// Context to store other options
|
// Context to store other options
|
||||||
Context context.Context
|
Context context.Context
|
||||||
}
|
}
|
||||||
@@ -213,7 +216,7 @@ func NewTokenOptions(opts ...TokenOption) TokenOptions {
|
|||||||
o(&options)
|
o(&options)
|
||||||
}
|
}
|
||||||
|
|
||||||
// set defualt expiry of token
|
// set default expiry of token
|
||||||
if options.Expiry == 0 {
|
if options.Expiry == 0 {
|
||||||
options.Expiry = time.Minute
|
options.Expiry = time.Minute
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error {
|
|||||||
// not case sensitive.
|
// not case sensitive.
|
||||||
func include(slice []string, val string) bool {
|
func include(slice []string, val string) bool {
|
||||||
for _, s := range slice {
|
for _, s := range slice {
|
||||||
if strings.ToLower(s) == strings.ToLower(val) {
|
if strings.EqualFold(s, val) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "",
|
Scope: "",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
},
|
},
|
||||||
@@ -52,7 +52,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Name: "CatchallPublicNoAccount",
|
Name: "CatchallPublicNoAccount",
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "",
|
Scope: "",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
},
|
},
|
||||||
@@ -63,7 +63,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
},
|
},
|
||||||
@@ -73,7 +73,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Name: "CatchallPrivateNoAccount",
|
Name: "CatchallPrivateNoAccount",
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
},
|
},
|
||||||
@@ -85,7 +85,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: srvResource.Type,
|
Type: srvResource.Type,
|
||||||
@@ -100,7 +100,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: srvResource.Type,
|
Type: srvResource.Type,
|
||||||
@@ -118,7 +118,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Scopes: []string{"neededscope"},
|
Scopes: []string{"neededscope"},
|
||||||
},
|
},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "neededscope",
|
Scope: "neededscope",
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
},
|
},
|
||||||
@@ -131,7 +131,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Scopes: []string{"neededscope"},
|
Scopes: []string{"neededscope"},
|
||||||
},
|
},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "invalidscope",
|
Scope: "invalidscope",
|
||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
},
|
},
|
||||||
@@ -143,7 +143,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessDenied,
|
Access: AccessDenied,
|
||||||
@@ -156,7 +156,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessDenied,
|
Access: AccessDenied,
|
||||||
@@ -169,13 +169,13 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessGranted,
|
Access: AccessGranted,
|
||||||
Priority: 1,
|
Priority: 1,
|
||||||
},
|
},
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessDenied,
|
Access: AccessDenied,
|
||||||
@@ -188,13 +188,13 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: srvResource,
|
Resource: srvResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessGranted,
|
Access: AccessGranted,
|
||||||
Priority: 0,
|
Priority: 0,
|
||||||
},
|
},
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: catchallResource,
|
Resource: catchallResource,
|
||||||
Access: AccessDenied,
|
Access: AccessDenied,
|
||||||
@@ -208,7 +208,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
},
|
},
|
||||||
@@ -219,7 +219,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: webResource.Type,
|
Type: webResource.Type,
|
||||||
@@ -235,7 +235,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: webResource.Type,
|
Type: webResource.Type,
|
||||||
@@ -250,7 +250,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: webResource.Type,
|
Type: webResource.Type,
|
||||||
@@ -265,7 +265,7 @@ func TestVerify(t *testing.T) {
|
|||||||
Resource: webResource,
|
Resource: webResource,
|
||||||
Account: &Account{},
|
Account: &Account{},
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
&Rule{
|
{
|
||||||
Scope: "*",
|
Scope: "*",
|
||||||
Resource: &Resource{
|
Resource: &Resource{
|
||||||
Type: webResource.Type,
|
Type: webResource.Type,
|
||||||
|
|||||||
@@ -1,28 +1,27 @@
|
|||||||
// Package broker is an interface used for asynchronous messaging
|
// Package broker is an interface used for asynchronous messaging
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
var (
|
||||||
|
DefaultBroker Broker = NewBroker()
|
||||||
|
)
|
||||||
|
|
||||||
// Broker is an interface used for asynchronous messaging.
|
// Broker is an interface used for asynchronous messaging.
|
||||||
type Broker interface {
|
type Broker interface {
|
||||||
Init(...Option) error
|
Init(...Option) error
|
||||||
Options() Options
|
Options() Options
|
||||||
Address() string
|
Address() string
|
||||||
Connect() error
|
Connect(context.Context) error
|
||||||
Disconnect() error
|
Disconnect(context.Context) error
|
||||||
Publish(topic string, m *Message, opts ...PublishOption) error
|
Publish(context.Context, string, *Message, ...PublishOption) error
|
||||||
Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
|
Subscribe(context.Context, string, Handler, ...SubscribeOption) (Subscriber, error)
|
||||||
String() string
|
String() string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handler is used to process messages via a subscription of a topic.
|
// Handler is used to process messages via a subscription of a topic.
|
||||||
// The handler is passed a publication interface which contains the
|
|
||||||
// message and optional Ack method to acknowledge receipt of the message.
|
|
||||||
type Handler func(Event) error
|
type Handler func(Event) error
|
||||||
|
|
||||||
type Message struct {
|
|
||||||
Header map[string]string
|
|
||||||
Body []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// Event is given to a subscription handler for processing
|
// Event is given to a subscription handler for processing
|
||||||
type Event interface {
|
type Event interface {
|
||||||
Topic() string
|
Topic() string
|
||||||
@@ -31,9 +30,15 @@ type Event interface {
|
|||||||
Error() error
|
Error() error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Message is used to transfer data
|
||||||
|
type Message struct {
|
||||||
|
Header map[string]string // contains message metadata
|
||||||
|
Body []byte // contains message body
|
||||||
|
}
|
||||||
|
|
||||||
// Subscriber is a convenience return type for the Subscribe method
|
// Subscriber is a convenience return type for the Subscribe method
|
||||||
type Subscriber interface {
|
type Subscriber interface {
|
||||||
Options() SubscribeOptions
|
Options() SubscribeOptions
|
||||||
Topic() string
|
Topic() string
|
||||||
Unsubscribe() error
|
Unsubscribe(context.Context) error
|
||||||
}
|
}
|
||||||
|
|||||||
46
broker/context.go
Normal file
46
broker/context.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
|
type brokerKey struct{}
|
||||||
|
|
||||||
|
func FromContext(ctx context.Context) (Broker, bool) {
|
||||||
|
c, ok := ctx.Value(brokerKey{}).(Broker)
|
||||||
|
return c, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewContext(ctx context.Context, s Broker) context.Context {
|
||||||
|
return context.WithValue(ctx, brokerKey{}, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSubscribeOption returns a function to setup a context with given value
|
||||||
|
func SetSubscribeOption(k, v interface{}) SubscribeOption {
|
||||||
|
return func(o *SubscribeOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetOption returns a function to setup a context with given value
|
||||||
|
func SetOption(k, v interface{}) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPublishOption returns a function to setup a context with given value
|
||||||
|
func SetPublishOption(k, v interface{}) PublishOption {
|
||||||
|
return func(o *PublishOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,713 +0,0 @@
|
|||||||
// Package http provides a http based message broker
|
|
||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"math/rand"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/codec/json"
|
|
||||||
merr "github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/cache"
|
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
|
||||||
maddr "github.com/micro/go-micro/v3/util/addr"
|
|
||||||
mnet "github.com/micro/go-micro/v3/util/net"
|
|
||||||
mls "github.com/micro/go-micro/v3/util/tls"
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTP Broker is a point to point async broker
|
|
||||||
type httpBroker struct {
|
|
||||||
id string
|
|
||||||
address string
|
|
||||||
opts broker.Options
|
|
||||||
|
|
||||||
mux *http.ServeMux
|
|
||||||
|
|
||||||
c *http.Client
|
|
||||||
r registry.Registry
|
|
||||||
|
|
||||||
sync.RWMutex
|
|
||||||
subscribers map[string][]*httpSubscriber
|
|
||||||
running bool
|
|
||||||
exit chan chan error
|
|
||||||
|
|
||||||
// offline message inbox
|
|
||||||
mtx sync.RWMutex
|
|
||||||
inbox map[string][][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
type httpSubscriber struct {
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
id string
|
|
||||||
topic string
|
|
||||||
fn broker.Handler
|
|
||||||
svc *registry.Service
|
|
||||||
hb *httpBroker
|
|
||||||
}
|
|
||||||
|
|
||||||
type httpEvent struct {
|
|
||||||
m *broker.Message
|
|
||||||
t string
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
DefaultPath = "/"
|
|
||||||
DefaultAddress = "127.0.0.1:0"
|
|
||||||
serviceName = "micro.http.broker"
|
|
||||||
broadcastVersion = "ff.http.broadcast"
|
|
||||||
registerTTL = time.Minute
|
|
||||||
registerInterval = time.Second * 30
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
rand.Seed(time.Now().Unix())
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTransport(config *tls.Config) *http.Transport {
|
|
||||||
if config == nil {
|
|
||||||
config = &tls.Config{
|
|
||||||
InsecureSkipVerify: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dialTLS := func(network string, addr string) (net.Conn, error) {
|
|
||||||
return tls.Dial(network, addr, config)
|
|
||||||
}
|
|
||||||
|
|
||||||
t := &http.Transport{
|
|
||||||
Proxy: http.ProxyFromEnvironment,
|
|
||||||
Dial: (&net.Dialer{
|
|
||||||
Timeout: 30 * time.Second,
|
|
||||||
KeepAlive: 30 * time.Second,
|
|
||||||
}).Dial,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
DialTLS: dialTLS,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(&t, func(tr **http.Transport) {
|
|
||||||
(*tr).CloseIdleConnections()
|
|
||||||
})
|
|
||||||
|
|
||||||
// setup http2
|
|
||||||
http2.ConfigureTransport(t)
|
|
||||||
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
func newHttpBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
options := broker.Options{
|
|
||||||
Codec: json.Marshaler{},
|
|
||||||
Context: context.TODO(),
|
|
||||||
Registry: mdns.NewRegistry(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set address
|
|
||||||
addr := DefaultAddress
|
|
||||||
|
|
||||||
if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 {
|
|
||||||
addr = options.Addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
h := &httpBroker{
|
|
||||||
id: uuid.New().String(),
|
|
||||||
address: addr,
|
|
||||||
opts: options,
|
|
||||||
r: options.Registry,
|
|
||||||
c: &http.Client{Transport: newTransport(options.TLSConfig)},
|
|
||||||
subscribers: make(map[string][]*httpSubscriber),
|
|
||||||
exit: make(chan chan error),
|
|
||||||
mux: http.NewServeMux(),
|
|
||||||
inbox: make(map[string][][]byte),
|
|
||||||
}
|
|
||||||
|
|
||||||
// specify the message handler
|
|
||||||
h.mux.Handle(DefaultPath, h)
|
|
||||||
|
|
||||||
// get optional handlers
|
|
||||||
if h.opts.Context != nil {
|
|
||||||
handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler)
|
|
||||||
if ok {
|
|
||||||
for pattern, handler := range handlers {
|
|
||||||
h.mux.Handle(pattern, handler)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpEvent) Ack() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpEvent) Error() error {
|
|
||||||
return h.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpEvent) Message() *broker.Message {
|
|
||||||
return h.m
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpEvent) Topic() string {
|
|
||||||
return h.t
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Options() broker.SubscribeOptions {
|
|
||||||
return h.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Topic() string {
|
|
||||||
return h.topic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Unsubscribe() error {
|
|
||||||
return h.hb.unsubscribe(h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) saveMessage(topic string, msg []byte) {
|
|
||||||
h.mtx.Lock()
|
|
||||||
defer h.mtx.Unlock()
|
|
||||||
|
|
||||||
// get messages
|
|
||||||
c := h.inbox[topic]
|
|
||||||
|
|
||||||
// save message
|
|
||||||
c = append(c, msg)
|
|
||||||
|
|
||||||
// max length 64
|
|
||||||
if len(c) > 64 {
|
|
||||||
c = c[:64]
|
|
||||||
}
|
|
||||||
|
|
||||||
// save inbox
|
|
||||||
h.inbox[topic] = c
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) getMessage(topic string, num int) [][]byte {
|
|
||||||
h.mtx.Lock()
|
|
||||||
defer h.mtx.Unlock()
|
|
||||||
|
|
||||||
// get messages
|
|
||||||
c, ok := h.inbox[topic]
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// more message than requests
|
|
||||||
if len(c) >= num {
|
|
||||||
msg := c[:num]
|
|
||||||
h.inbox[topic] = c[num:]
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// reset inbox
|
|
||||||
h.inbox[topic] = nil
|
|
||||||
|
|
||||||
// return all messages
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) subscribe(s *httpSubscriber) error {
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
if err := h.r.Register(s.svc, registry.RegisterTTL(registerTTL)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
h.subscribers[s.topic] = append(h.subscribers[s.topic], s)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) unsubscribe(s *httpSubscriber) error {
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
//nolint:prealloc
|
|
||||||
var subscribers []*httpSubscriber
|
|
||||||
|
|
||||||
// look for subscriber
|
|
||||||
for _, sub := range h.subscribers[s.topic] {
|
|
||||||
// deregister and skip forward
|
|
||||||
if sub == s {
|
|
||||||
_ = h.r.Deregister(sub.svc)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// keep subscriber
|
|
||||||
subscribers = append(subscribers, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set subscribers
|
|
||||||
h.subscribers[s.topic] = subscribers
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) run(l net.Listener) {
|
|
||||||
t := time.NewTicker(registerInterval)
|
|
||||||
defer t.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
// heartbeat for each subscriber
|
|
||||||
case <-t.C:
|
|
||||||
h.RLock()
|
|
||||||
for _, subs := range h.subscribers {
|
|
||||||
for _, sub := range subs {
|
|
||||||
_ = h.r.Register(sub.svc, registry.RegisterTTL(registerTTL))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
// received exit signal
|
|
||||||
case ch := <-h.exit:
|
|
||||||
ch <- l.Close()
|
|
||||||
h.RLock()
|
|
||||||
for _, subs := range h.subscribers {
|
|
||||||
for _, sub := range subs {
|
|
||||||
_ = h.r.Deregister(sub.svc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
if req.Method != "POST" {
|
|
||||||
err := merr.BadRequest("go.micro.broker", "Method not allowed")
|
|
||||||
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer req.Body.Close()
|
|
||||||
|
|
||||||
req.ParseForm()
|
|
||||||
|
|
||||||
b, err := ioutil.ReadAll(req.Body)
|
|
||||||
if err != nil {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var m *broker.Message
|
|
||||||
if err = h.opts.Codec.Unmarshal(b, &m); err != nil {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
topic := m.Header["Micro-Topic"]
|
|
||||||
//delete(m.Header, ":topic")
|
|
||||||
|
|
||||||
if len(topic) == 0 {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Topic not found")
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p := &httpEvent{m: m, t: topic}
|
|
||||||
id := req.Form.Get("id")
|
|
||||||
|
|
||||||
//nolint:prealloc
|
|
||||||
var subs []broker.Handler
|
|
||||||
|
|
||||||
h.RLock()
|
|
||||||
for _, subscriber := range h.subscribers[topic] {
|
|
||||||
if id != subscriber.id {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
subs = append(subs, subscriber.fn)
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
// execute the handler
|
|
||||||
for _, fn := range subs {
|
|
||||||
p.err = fn(p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Address() string {
|
|
||||||
h.RLock()
|
|
||||||
defer h.RUnlock()
|
|
||||||
return h.address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Connect() error {
|
|
||||||
h.RLock()
|
|
||||||
if h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
var l net.Listener
|
|
||||||
var err error
|
|
||||||
|
|
||||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
|
||||||
config := h.opts.TLSConfig
|
|
||||||
|
|
||||||
fn := func(addr string) (net.Listener, error) {
|
|
||||||
if config == nil {
|
|
||||||
hosts := []string{addr}
|
|
||||||
|
|
||||||
// check if its a valid host:port
|
|
||||||
if host, _, err := net.SplitHostPort(addr); err == nil {
|
|
||||||
if len(host) == 0 {
|
|
||||||
hosts = maddr.IPs()
|
|
||||||
} else {
|
|
||||||
hosts = []string{host}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate a certificate
|
|
||||||
cert, err := mls.Certificate(hosts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
config = &tls.Config{Certificates: []tls.Certificate{cert}}
|
|
||||||
}
|
|
||||||
return tls.Listen("tcp", addr, config)
|
|
||||||
}
|
|
||||||
|
|
||||||
l, err = mnet.Listen(h.address, fn)
|
|
||||||
} else {
|
|
||||||
fn := func(addr string) (net.Listener, error) {
|
|
||||||
return net.Listen("tcp", addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
l, err = mnet.Listen(h.address, fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := h.address
|
|
||||||
h.address = l.Addr().String()
|
|
||||||
|
|
||||||
go http.Serve(l, h.mux)
|
|
||||||
go func() {
|
|
||||||
h.run(l)
|
|
||||||
h.Lock()
|
|
||||||
h.opts.Addrs = []string{addr}
|
|
||||||
h.address = addr
|
|
||||||
h.Unlock()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// get registry
|
|
||||||
reg := h.opts.Registry
|
|
||||||
if reg == nil {
|
|
||||||
reg = mdns.NewRegistry()
|
|
||||||
}
|
|
||||||
// set cache
|
|
||||||
h.r = cache.New(reg)
|
|
||||||
|
|
||||||
// set running
|
|
||||||
h.running = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Disconnect() error {
|
|
||||||
h.RLock()
|
|
||||||
if !h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
// stop cache
|
|
||||||
rc, ok := h.r.(cache.Cache)
|
|
||||||
if ok {
|
|
||||||
rc.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// exit and return err
|
|
||||||
ch := make(chan error)
|
|
||||||
h.exit <- ch
|
|
||||||
err := <-ch
|
|
||||||
|
|
||||||
// set not running
|
|
||||||
h.running = false
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Init(opts ...broker.Option) error {
|
|
||||||
h.RLock()
|
|
||||||
if h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return errors.New("cannot init while connected")
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&h.opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(h.opts.Addrs) > 0 && len(h.opts.Addrs[0]) > 0 {
|
|
||||||
h.address = h.opts.Addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(h.id) == 0 {
|
|
||||||
h.id = "go.micro.http.broker-" + uuid.New().String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// get registry
|
|
||||||
reg := h.opts.Registry
|
|
||||||
if reg == nil {
|
|
||||||
reg = mdns.NewRegistry()
|
|
||||||
}
|
|
||||||
|
|
||||||
// get cache
|
|
||||||
if rc, ok := h.r.(cache.Cache); ok {
|
|
||||||
rc.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// set registry
|
|
||||||
h.r = cache.New(reg)
|
|
||||||
|
|
||||||
// reconfigure tls config
|
|
||||||
if c := h.opts.TLSConfig; c != nil {
|
|
||||||
h.c = &http.Client{
|
|
||||||
Transport: newTransport(c),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Options() broker.Options {
|
|
||||||
return h.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
|
||||||
// create the message first
|
|
||||||
m := &broker.Message{
|
|
||||||
Header: make(map[string]string),
|
|
||||||
Body: msg.Body,
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range msg.Header {
|
|
||||||
m.Header[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
m.Header["Micro-Topic"] = topic
|
|
||||||
|
|
||||||
// encode the message
|
|
||||||
b, err := h.opts.Codec.Marshal(m)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// save the message
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
|
|
||||||
// now attempt to get the service
|
|
||||||
h.RLock()
|
|
||||||
s, err := h.r.GetService(serviceName)
|
|
||||||
if err != nil {
|
|
||||||
h.RUnlock()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
pub := func(node *registry.Node, t string, b []byte) error {
|
|
||||||
scheme := "http"
|
|
||||||
|
|
||||||
// check if secure is added in metadata
|
|
||||||
if node.Metadata["secure"] == "true" {
|
|
||||||
scheme = "https"
|
|
||||||
}
|
|
||||||
|
|
||||||
vals := url.Values{}
|
|
||||||
vals.Add("id", node.Id)
|
|
||||||
|
|
||||||
uri := fmt.Sprintf("%s://%s%s?%s", scheme, node.Address, DefaultPath, vals.Encode())
|
|
||||||
r, err := h.c.Post(uri, "application/json", bytes.NewReader(b))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// discard response body
|
|
||||||
io.Copy(ioutil.Discard, r.Body)
|
|
||||||
r.Body.Close()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := func(s []*registry.Service, b []byte) {
|
|
||||||
for _, service := range s {
|
|
||||||
var nodes []*registry.Node
|
|
||||||
|
|
||||||
for _, node := range service.Nodes {
|
|
||||||
// only use nodes tagged with broker http
|
|
||||||
if node.Metadata["broker"] != "http" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// look for nodes for the topic
|
|
||||||
if node.Metadata["topic"] != topic {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes = append(nodes, node)
|
|
||||||
}
|
|
||||||
|
|
||||||
// only process if we have nodes
|
|
||||||
if len(nodes) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
switch service.Version {
|
|
||||||
// broadcast version means broadcast to all nodes
|
|
||||||
case broadcastVersion:
|
|
||||||
var success bool
|
|
||||||
|
|
||||||
// publish to all nodes
|
|
||||||
for _, node := range nodes {
|
|
||||||
// publish async
|
|
||||||
if err := pub(node, topic, b); err == nil {
|
|
||||||
success = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// save if it failed to publish at least once
|
|
||||||
if !success {
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// select node to publish to
|
|
||||||
node := nodes[rand.Int()%len(nodes)]
|
|
||||||
|
|
||||||
// publish async to one node
|
|
||||||
if err := pub(node, topic, b); err != nil {
|
|
||||||
// if failed save it
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// do the rest async
|
|
||||||
go func() {
|
|
||||||
// get a third of the backlog
|
|
||||||
messages := h.getMessage(topic, 8)
|
|
||||||
delay := (len(messages) > 1)
|
|
||||||
|
|
||||||
// publish all the messages
|
|
||||||
for _, msg := range messages {
|
|
||||||
// serialize here
|
|
||||||
srv(s, msg)
|
|
||||||
|
|
||||||
// sending a backlog of messages
|
|
||||||
if delay {
|
|
||||||
time.Sleep(time.Millisecond * 100)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
var err error
|
|
||||||
var host, port string
|
|
||||||
options := broker.NewSubscribeOptions(opts...)
|
|
||||||
|
|
||||||
// parse address for host, port
|
|
||||||
host, port, err = net.SplitHostPort(h.Address())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := maddr.Extract(host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var secure bool
|
|
||||||
|
|
||||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
|
||||||
secure = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// register service
|
|
||||||
node := ®istry.Node{
|
|
||||||
Id: topic + "-" + h.id,
|
|
||||||
Address: mnet.HostPort(addr, port),
|
|
||||||
Metadata: map[string]string{
|
|
||||||
"secure": fmt.Sprintf("%t", secure),
|
|
||||||
"broker": "http",
|
|
||||||
"topic": topic,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// check for queue group or broadcast queue
|
|
||||||
version := options.Queue
|
|
||||||
if len(version) == 0 {
|
|
||||||
version = broadcastVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
service := ®istry.Service{
|
|
||||||
Name: serviceName,
|
|
||||||
Version: version,
|
|
||||||
Nodes: []*registry.Node{node},
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate subscriber
|
|
||||||
subscriber := &httpSubscriber{
|
|
||||||
opts: options,
|
|
||||||
hb: h,
|
|
||||||
id: node.Id,
|
|
||||||
topic: topic,
|
|
||||||
fn: handler,
|
|
||||||
svc: service,
|
|
||||||
}
|
|
||||||
|
|
||||||
// subscribe now
|
|
||||||
if err := h.subscribe(subscriber); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// return the subscriber
|
|
||||||
return subscriber, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) String() string {
|
|
||||||
return "http"
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBroker returns a new http broker
|
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
return newHttpBroker(opts...)
|
|
||||||
}
|
|
||||||
@@ -1,384 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/memory"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// mock data
|
|
||||||
testData = map[string][]*registry.Service{
|
|
||||||
"foo": {
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.0",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.0-123",
|
|
||||||
Address: "localhost:9999",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.0-321",
|
|
||||||
Address: "localhost:9999",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.1",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.1-321",
|
|
||||||
Address: "localhost:6666",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.3",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.3-345",
|
|
||||||
Address: "localhost:8888",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func newTestRegistry() registry.Registry {
|
|
||||||
return memory.NewRegistry(memory.Services(testData))
|
|
||||||
}
|
|
||||||
|
|
||||||
func sub(be *testing.B, c int) {
|
|
||||||
be.StopTimer()
|
|
||||||
m := newTestRegistry()
|
|
||||||
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
topic := uuid.New().String()
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
be.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var subs []broker.Subscriber
|
|
||||||
done := make(chan bool, c)
|
|
||||||
|
|
||||||
for i := 0; i < c; i++ {
|
|
||||||
sub, err := b.Subscribe(topic, func(p broker.Event) error {
|
|
||||||
done <- true
|
|
||||||
m := p.Message()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}, broker.Queue("shared"))
|
|
||||||
if err != nil {
|
|
||||||
be.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
subs = append(subs, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < be.N; i++ {
|
|
||||||
be.StartTimer()
|
|
||||||
if err := b.Publish(topic, msg); err != nil {
|
|
||||||
be.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
<-done
|
|
||||||
be.StopTimer()
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
|
||||||
sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func pub(be *testing.B, c int) {
|
|
||||||
be.StopTimer()
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
topic := uuid.New().String()
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
be.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
done := make(chan bool, c*4)
|
|
||||||
|
|
||||||
sub, err := b.Subscribe(topic, func(p broker.Event) error {
|
|
||||||
done <- true
|
|
||||||
m := p.Message()
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}, broker.Queue("shared"))
|
|
||||||
if err != nil {
|
|
||||||
be.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
ch := make(chan int, c*4)
|
|
||||||
be.StartTimer()
|
|
||||||
|
|
||||||
for i := 0; i < c; i++ {
|
|
||||||
go func() {
|
|
||||||
for range ch {
|
|
||||||
if err := b.Publish(topic, msg); err != nil {
|
|
||||||
be.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-done:
|
|
||||||
case <-time.After(time.Second):
|
|
||||||
}
|
|
||||||
wg.Done()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < be.N; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
ch <- i
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
be.StopTimer()
|
|
||||||
sub.Unsubscribe()
|
|
||||||
close(ch)
|
|
||||||
close(done)
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
done := make(chan bool)
|
|
||||||
|
|
||||||
sub, err := b.Subscribe("test", func(p broker.Event) error {
|
|
||||||
m := p.Message()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
close(done)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-done
|
|
||||||
sub.Unsubscribe()
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConcurrentSubBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var subs []broker.Subscriber
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
sub, err := b.Subscribe("test", func(p broker.Event) error {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
m := p.Message()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Add(1)
|
|
||||||
subs = append(subs, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
|
||||||
sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConcurrentPubBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
sub, err := b.Subscribe("test", func(p broker.Event) error {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
m := p.Message()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
sub.Unsubscribe()
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub1(b *testing.B) {
|
|
||||||
sub(b, 1)
|
|
||||||
}
|
|
||||||
func BenchmarkSub8(b *testing.B) {
|
|
||||||
sub(b, 8)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub32(b *testing.B) {
|
|
||||||
sub(b, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub64(b *testing.B) {
|
|
||||||
sub(b, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub128(b *testing.B) {
|
|
||||||
sub(b, 128)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub1(b *testing.B) {
|
|
||||||
pub(b, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub8(b *testing.B) {
|
|
||||||
pub(b, 8)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub32(b *testing.B) {
|
|
||||||
pub(b, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub64(b *testing.B) {
|
|
||||||
pub(b, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub128(b *testing.B) {
|
|
||||||
pub(b, 128)
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handle registers the handler for the given pattern.
|
|
||||||
func Handle(pattern string, handler http.Handler) broker.Option {
|
|
||||||
return func(o *broker.Options) {
|
|
||||||
if o.Context == nil {
|
|
||||||
o.Context = context.Background()
|
|
||||||
}
|
|
||||||
handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler)
|
|
||||||
if !ok {
|
|
||||||
handlers = make(map[string]http.Handler)
|
|
||||||
}
|
|
||||||
handlers[pattern] = handler
|
|
||||||
o.Context = context.WithValue(o.Context, "http_handlers", handlers)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
// Package memory provides a memory broker
|
|
||||||
package memory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"math/rand"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
maddr "github.com/micro/go-micro/v3/util/addr"
|
|
||||||
mnet "github.com/micro/go-micro/v3/util/net"
|
|
||||||
)
|
|
||||||
|
|
||||||
type memoryBroker struct {
|
|
||||||
opts broker.Options
|
|
||||||
|
|
||||||
addr string
|
|
||||||
sync.RWMutex
|
|
||||||
connected bool
|
|
||||||
Subscribers map[string][]*memorySubscriber
|
|
||||||
}
|
|
||||||
|
|
||||||
type memoryEvent struct {
|
|
||||||
opts broker.Options
|
|
||||||
topic string
|
|
||||||
err error
|
|
||||||
message interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type memorySubscriber struct {
|
|
||||||
id string
|
|
||||||
topic string
|
|
||||||
exit chan bool
|
|
||||||
handler broker.Handler
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Options() broker.Options {
|
|
||||||
return m.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Address() string {
|
|
||||||
return m.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Connect() error {
|
|
||||||
m.Lock()
|
|
||||||
defer m.Unlock()
|
|
||||||
|
|
||||||
if m.connected {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// use 127.0.0.1 to avoid scan of all network interfaces
|
|
||||||
addr, err := maddr.Extract("127.0.0.1")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i := rand.Intn(20000)
|
|
||||||
// set addr with port
|
|
||||||
addr = mnet.HostPort(addr, 10000+i)
|
|
||||||
|
|
||||||
m.addr = addr
|
|
||||||
m.connected = true
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Disconnect() error {
|
|
||||||
m.Lock()
|
|
||||||
defer m.Unlock()
|
|
||||||
|
|
||||||
if !m.connected {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.connected = false
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Init(opts ...broker.Option) error {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&m.opts)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
|
||||||
m.RLock()
|
|
||||||
if !m.connected {
|
|
||||||
m.RUnlock()
|
|
||||||
return errors.New("not connected")
|
|
||||||
}
|
|
||||||
|
|
||||||
subs, ok := m.Subscribers[topic]
|
|
||||||
m.RUnlock()
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var v interface{}
|
|
||||||
if m.opts.Codec != nil {
|
|
||||||
buf, err := m.opts.Codec.Marshal(msg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
v = buf
|
|
||||||
} else {
|
|
||||||
v = msg
|
|
||||||
}
|
|
||||||
|
|
||||||
p := &memoryEvent{
|
|
||||||
topic: topic,
|
|
||||||
message: v,
|
|
||||||
opts: m.opts,
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
|
||||||
if err := sub.handler(p); err != nil {
|
|
||||||
p.err = err
|
|
||||||
if eh := m.opts.ErrorHandler; eh != nil {
|
|
||||||
eh(p)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
m.RLock()
|
|
||||||
if !m.connected {
|
|
||||||
m.RUnlock()
|
|
||||||
return nil, errors.New("not connected")
|
|
||||||
}
|
|
||||||
m.RUnlock()
|
|
||||||
|
|
||||||
var options broker.SubscribeOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
sub := &memorySubscriber{
|
|
||||||
exit: make(chan bool, 1),
|
|
||||||
id: uuid.New().String(),
|
|
||||||
topic: topic,
|
|
||||||
handler: handler,
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
|
|
||||||
m.Lock()
|
|
||||||
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
|
|
||||||
m.Unlock()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
<-sub.exit
|
|
||||||
m.Lock()
|
|
||||||
var newSubscribers []*memorySubscriber
|
|
||||||
for _, sb := range m.Subscribers[topic] {
|
|
||||||
if sb.id == sub.id {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newSubscribers = append(newSubscribers, sb)
|
|
||||||
}
|
|
||||||
m.Subscribers[topic] = newSubscribers
|
|
||||||
m.Unlock()
|
|
||||||
}()
|
|
||||||
|
|
||||||
return sub, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryBroker) String() string {
|
|
||||||
return "memory"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryEvent) Topic() string {
|
|
||||||
return m.topic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryEvent) Message() *broker.Message {
|
|
||||||
switch v := m.message.(type) {
|
|
||||||
case *broker.Message:
|
|
||||||
return v
|
|
||||||
case []byte:
|
|
||||||
msg := &broker.Message{}
|
|
||||||
if err := m.opts.Codec.Unmarshal(v, msg); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("[memory]: failed to unmarshal: %v\n", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryEvent) Ack() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryEvent) Error() error {
|
|
||||||
return m.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memorySubscriber) Options() broker.SubscribeOptions {
|
|
||||||
return m.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memorySubscriber) Topic() string {
|
|
||||||
return m.topic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memorySubscriber) Unsubscribe() error {
|
|
||||||
m.exit <- true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
options := broker.Options{
|
|
||||||
Context: context.Background(),
|
|
||||||
}
|
|
||||||
|
|
||||||
rand.Seed(time.Now().UnixNano())
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &memoryBroker{
|
|
||||||
opts: options,
|
|
||||||
Subscribers: make(map[string][]*memorySubscriber),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
package memory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestMemoryBroker(t *testing.T) {
|
|
||||||
b := NewBroker()
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
topic := "test"
|
|
||||||
count := 10
|
|
||||||
|
|
||||||
fn := func(p broker.Event) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
sub, err := b.Subscribe(topic, fn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected error subscribing %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
message := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"foo": "bar",
|
|
||||||
"id": fmt.Sprintf("%d", i),
|
|
||||||
},
|
|
||||||
Body: []byte(`hello world`),
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish(topic, message); err != nil {
|
|
||||||
t.Fatalf("Unexpected error publishing %d", i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := sub.Unsubscribe(); err != nil {
|
|
||||||
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setBrokerOption returns a function to setup a context with given value
|
|
||||||
func setBrokerOption(k, v interface{}) broker.Option {
|
|
||||||
return func(o *broker.Options) {
|
|
||||||
if o.Context == nil {
|
|
||||||
o.Context = context.Background()
|
|
||||||
}
|
|
||||||
o.Context = context.WithValue(o.Context, k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,322 +0,0 @@
|
|||||||
// Package nats provides a NATS broker
|
|
||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/codec/json"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type natsBroker struct {
|
|
||||||
sync.Once
|
|
||||||
sync.RWMutex
|
|
||||||
|
|
||||||
// indicate if we're connected
|
|
||||||
connected bool
|
|
||||||
|
|
||||||
addrs []string
|
|
||||||
conn *nats.Conn
|
|
||||||
opts broker.Options
|
|
||||||
nopts nats.Options
|
|
||||||
|
|
||||||
// should we drain the connection
|
|
||||||
drain bool
|
|
||||||
closeCh chan (error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type subscriber struct {
|
|
||||||
s *nats.Subscription
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
type publication struct {
|
|
||||||
t string
|
|
||||||
err error
|
|
||||||
m *broker.Message
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Topic() string {
|
|
||||||
return p.t
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Message() *broker.Message {
|
|
||||||
return p.m
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Ack() error {
|
|
||||||
// nats does not support acking
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Error() error {
|
|
||||||
return p.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Options() broker.SubscribeOptions {
|
|
||||||
return s.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Topic() string {
|
|
||||||
return s.s.Subject
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Unsubscribe() error {
|
|
||||||
return s.s.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Address() string {
|
|
||||||
if n.conn != nil && n.conn.IsConnected() {
|
|
||||||
return n.conn.ConnectedUrl()
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(n.addrs) > 0 {
|
|
||||||
return n.addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) setAddrs(addrs []string) []string {
|
|
||||||
//nolint:prealloc
|
|
||||||
var cAddrs []string
|
|
||||||
for _, addr := range addrs {
|
|
||||||
if len(addr) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(addr, "nats://") {
|
|
||||||
addr = "nats://" + addr
|
|
||||||
}
|
|
||||||
cAddrs = append(cAddrs, addr)
|
|
||||||
}
|
|
||||||
if len(cAddrs) == 0 {
|
|
||||||
cAddrs = []string{nats.DefaultURL}
|
|
||||||
}
|
|
||||||
return cAddrs
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Connect() error {
|
|
||||||
n.Lock()
|
|
||||||
defer n.Unlock()
|
|
||||||
|
|
||||||
if n.connected {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
status := nats.CLOSED
|
|
||||||
if n.conn != nil {
|
|
||||||
status = n.conn.Status()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch status {
|
|
||||||
case nats.CONNECTED, nats.RECONNECTING, nats.CONNECTING:
|
|
||||||
n.connected = true
|
|
||||||
return nil
|
|
||||||
default: // DISCONNECTED or CLOSED or DRAINING
|
|
||||||
opts := n.nopts
|
|
||||||
opts.Servers = n.addrs
|
|
||||||
opts.Secure = n.opts.Secure
|
|
||||||
opts.TLSConfig = n.opts.TLSConfig
|
|
||||||
|
|
||||||
// secure might not be set
|
|
||||||
if n.opts.TLSConfig != nil {
|
|
||||||
opts.Secure = true
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := opts.Connect()
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.WarnLevel, logger.DefaultLogger) {
|
|
||||||
logger.Warnf("Error connecting to broker: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
n.conn = c
|
|
||||||
n.connected = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Disconnect() error {
|
|
||||||
n.Lock()
|
|
||||||
defer n.Unlock()
|
|
||||||
|
|
||||||
// drain the connection if specified
|
|
||||||
if n.drain {
|
|
||||||
n.conn.Drain()
|
|
||||||
n.closeCh <- nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// close the client connection
|
|
||||||
n.conn.Close()
|
|
||||||
|
|
||||||
// set not connected
|
|
||||||
n.connected = false
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Init(opts ...broker.Option) error {
|
|
||||||
n.setOption(opts...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Options() broker.Options {
|
|
||||||
return n.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
|
||||||
n.RLock()
|
|
||||||
defer n.RUnlock()
|
|
||||||
|
|
||||||
if n.conn == nil {
|
|
||||||
return errors.New("not connected")
|
|
||||||
}
|
|
||||||
|
|
||||||
b, err := n.opts.Codec.Marshal(msg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return n.conn.Publish(topic, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
n.RLock()
|
|
||||||
if n.conn == nil {
|
|
||||||
n.RUnlock()
|
|
||||||
return nil, errors.New("not connected")
|
|
||||||
}
|
|
||||||
n.RUnlock()
|
|
||||||
|
|
||||||
opt := broker.SubscribeOptions{
|
|
||||||
AutoAck: true,
|
|
||||||
Context: context.Background(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn := func(msg *nats.Msg) {
|
|
||||||
var m broker.Message
|
|
||||||
pub := &publication{t: msg.Subject}
|
|
||||||
eh := n.opts.ErrorHandler
|
|
||||||
err := n.opts.Codec.Unmarshal(msg.Data, &m)
|
|
||||||
pub.err = err
|
|
||||||
pub.m = &m
|
|
||||||
if err != nil {
|
|
||||||
m.Body = msg.Data
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
if eh != nil {
|
|
||||||
eh(pub)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := handler(pub); err != nil {
|
|
||||||
pub.err = err
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
if eh != nil {
|
|
||||||
eh(pub)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var sub *nats.Subscription
|
|
||||||
var err error
|
|
||||||
|
|
||||||
n.RLock()
|
|
||||||
if len(opt.Queue) > 0 {
|
|
||||||
sub, err = n.conn.QueueSubscribe(topic, opt.Queue, fn)
|
|
||||||
} else {
|
|
||||||
sub, err = n.conn.Subscribe(topic, fn)
|
|
||||||
}
|
|
||||||
n.RUnlock()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &subscriber{s: sub, opts: opt}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) String() string {
|
|
||||||
return "nats"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) setOption(opts ...broker.Option) {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&n.opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
n.Once.Do(func() {
|
|
||||||
n.nopts = nats.GetDefaultOptions()
|
|
||||||
})
|
|
||||||
|
|
||||||
if nopts, ok := n.opts.Context.Value(optionsKey{}).(nats.Options); ok {
|
|
||||||
n.nopts = nopts
|
|
||||||
}
|
|
||||||
|
|
||||||
// broker.Options have higher priority than nats.Options
|
|
||||||
// only if Addrs, Secure or TLSConfig were not set through a broker.Option
|
|
||||||
// we read them from nats.Option
|
|
||||||
if len(n.opts.Addrs) == 0 {
|
|
||||||
n.opts.Addrs = n.nopts.Servers
|
|
||||||
}
|
|
||||||
|
|
||||||
if !n.opts.Secure {
|
|
||||||
n.opts.Secure = n.nopts.Secure
|
|
||||||
}
|
|
||||||
|
|
||||||
if n.opts.TLSConfig == nil {
|
|
||||||
n.opts.TLSConfig = n.nopts.TLSConfig
|
|
||||||
}
|
|
||||||
n.addrs = n.setAddrs(n.opts.Addrs)
|
|
||||||
|
|
||||||
if n.opts.Context.Value(drainConnectionKey{}) != nil {
|
|
||||||
n.drain = true
|
|
||||||
n.closeCh = make(chan error)
|
|
||||||
n.nopts.ClosedCB = n.onClose
|
|
||||||
n.nopts.AsyncErrorCB = n.onAsyncError
|
|
||||||
n.nopts.DisconnectedErrCB = n.onDisconnectedError
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onClose(conn *nats.Conn) {
|
|
||||||
n.closeCh <- nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onAsyncError(conn *nats.Conn, sub *nats.Subscription, err error) {
|
|
||||||
// There are kinds of different async error nats might callback, but we are interested
|
|
||||||
// in ErrDrainTimeout only here.
|
|
||||||
if err == nats.ErrDrainTimeout {
|
|
||||||
n.closeCh <- err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onDisconnectedError(conn *nats.Conn, err error) {
|
|
||||||
n.closeCh <- err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
options := broker.Options{
|
|
||||||
// Default codec
|
|
||||||
Codec: json.Marshaler{},
|
|
||||||
Context: context.Background(),
|
|
||||||
Registry: mdns.NewRegistry(),
|
|
||||||
}
|
|
||||||
|
|
||||||
n := &natsBroker{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
n.setOption(opts...)
|
|
||||||
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
var addrTestCases = []struct {
|
|
||||||
name string
|
|
||||||
description string
|
|
||||||
addrs map[string]string // expected address : set address
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
"brokerOpts",
|
|
||||||
"set broker addresses through a broker.Option in constructor",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"brokerInit",
|
|
||||||
"set broker addresses through a broker.Option in broker.Init()",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"natsOpts",
|
|
||||||
"set broker addresses through the nats.Option in constructor",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"default",
|
|
||||||
"check if default Address is set correctly",
|
|
||||||
map[string]string{
|
|
||||||
"nats://127.0.0.1:4222": "",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestInitAddrs tests issue #100. Ensures that if the addrs is set by an option in init it will be used.
|
|
||||||
func TestInitAddrs(t *testing.T) {
|
|
||||||
|
|
||||||
for _, tc := range addrTestCases {
|
|
||||||
t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {
|
|
||||||
|
|
||||||
var br broker.Broker
|
|
||||||
var addrs []string
|
|
||||||
|
|
||||||
for _, addr := range tc.addrs {
|
|
||||||
addrs = append(addrs, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch tc.name {
|
|
||||||
case "brokerOpts":
|
|
||||||
// we know that there are just two addrs in the dict
|
|
||||||
br = NewBroker(broker.Addrs(addrs[0], addrs[1]))
|
|
||||||
br.Init()
|
|
||||||
case "brokerInit":
|
|
||||||
br = NewBroker()
|
|
||||||
// we know that there are just two addrs in the dict
|
|
||||||
br.Init(broker.Addrs(addrs[0], addrs[1]))
|
|
||||||
case "natsOpts":
|
|
||||||
nopts := nats.GetDefaultOptions()
|
|
||||||
nopts.Servers = addrs
|
|
||||||
br = NewBroker(Options(nopts))
|
|
||||||
br.Init()
|
|
||||||
case "default":
|
|
||||||
br = NewBroker()
|
|
||||||
br.Init()
|
|
||||||
}
|
|
||||||
|
|
||||||
natsBroker, ok := br.(*natsBroker)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("Expected broker to be of types *natsBroker")
|
|
||||||
}
|
|
||||||
// check if the same amount of addrs we set has actually been set, default
|
|
||||||
// have only 1 address nats://127.0.0.1:4222 (current nats code) or
|
|
||||||
// nats://localhost:4222 (older code version)
|
|
||||||
if len(natsBroker.addrs) != len(tc.addrs) && tc.name != "default" {
|
|
||||||
t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
|
|
||||||
len(natsBroker.addrs), len(tc.addrs))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, addr := range natsBroker.addrs {
|
|
||||||
_, ok := tc.addrs[addr]
|
|
||||||
if !ok {
|
|
||||||
t.Errorf("Expected '%s' has not been set", addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type optionsKey struct{}
|
|
||||||
type drainConnectionKey struct{}
|
|
||||||
|
|
||||||
// Options accepts nats.Options
|
|
||||||
func Options(opts nats.Options) broker.Option {
|
|
||||||
return setBrokerOption(optionsKey{}, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DrainConnection will drain subscription on close
|
|
||||||
func DrainConnection() broker.Option {
|
|
||||||
return setBrokerOption(drainConnectionKey{}, struct{}{})
|
|
||||||
}
|
|
||||||
77
broker/noop.go
Normal file
77
broker/noop.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type noopBroker struct {
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
|
||||||
|
type noopSubscriber struct {
|
||||||
|
topic string
|
||||||
|
opts SubscribeOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBroker returns new noop broker
|
||||||
|
func NewBroker(opts ...Option) Broker {
|
||||||
|
return &noopBroker{opts: NewOptions(opts...)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initialize broker
|
||||||
|
func (n *noopBroker) Init(opts ...Option) error {
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&n.opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options returns broker Options
|
||||||
|
func (n *noopBroker) Options() Options {
|
||||||
|
return n.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
// Address returns broker address
|
||||||
|
func (n *noopBroker) Address() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect connects to broker
|
||||||
|
func (n *noopBroker) Connect(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disconnect disconnects from broker
|
||||||
|
func (n *noopBroker) Disconnect(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish publishes message to broker
|
||||||
|
func (n *noopBroker) Publish(ctx context.Context, topic string, m *Message, opts ...PublishOption) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe subscribes to broker topic
|
||||||
|
func (n *noopBroker) Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||||
|
options := NewSubscribeOptions(opts...)
|
||||||
|
return &noopSubscriber{topic: topic, opts: options}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// String return broker string representation
|
||||||
|
func (n *noopBroker) String() string {
|
||||||
|
return "noop"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options returns subscriber options
|
||||||
|
func (n *noopSubscriber) Options() SubscribeOptions {
|
||||||
|
return n.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOpic returns subscriber topic
|
||||||
|
func (n *noopSubscriber) Topic() string {
|
||||||
|
return n.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unsubscribe unsbscribes from broker topic
|
||||||
|
func (n *noopSubscriber) Unsubscribe(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -4,17 +4,20 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/codec"
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
"github.com/micro/go-micro/v3/registry"
|
"github.com/unistack-org/micro/v3/logger"
|
||||||
|
"github.com/unistack-org/micro/v3/registry"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Options struct
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Addrs []string
|
Addrs []string
|
||||||
Secure bool
|
Secure bool
|
||||||
Codec codec.Marshaler
|
Codec codec.Marshaler
|
||||||
|
|
||||||
// Handler executed when error happens in broker message
|
// Logger
|
||||||
// processing
|
Logger logger.Logger
|
||||||
|
// Handler executed when errors occur processing messages
|
||||||
ErrorHandler Handler
|
ErrorHandler Handler
|
||||||
|
|
||||||
TLSConfig *tls.Config
|
TLSConfig *tls.Config
|
||||||
@@ -25,49 +28,92 @@ type Options struct {
|
|||||||
Context context.Context
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewOptions create new Options
|
||||||
|
func NewOptions(opts ...Option) Options {
|
||||||
|
options := Options{
|
||||||
|
Registry: registry.DefaultRegistry,
|
||||||
|
Logger: logger.DefaultLogger,
|
||||||
|
Context: context.Background(),
|
||||||
|
}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&options)
|
||||||
|
}
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
// Context sets the context option
|
||||||
|
func Context(ctx context.Context) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
o.Context = ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublishOptions struct
|
||||||
type PublishOptions struct {
|
type PublishOptions struct {
|
||||||
// Other options for implementations of the interface
|
// Other options for implementations of the interface
|
||||||
// can be stored in a context
|
// can be stored in a context
|
||||||
Context context.Context
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewPublishOptions creates PublishOptions struct
|
||||||
|
func NewPublishOptions(opts ...PublishOption) PublishOptions {
|
||||||
|
options := PublishOptions{
|
||||||
|
Context: context.Background(),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range opts {
|
||||||
|
o(&options)
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeOptions struct
|
||||||
type SubscribeOptions struct {
|
type SubscribeOptions struct {
|
||||||
// AutoAck defaults to true. When a handler returns
|
// AutoAck ack messages if handler returns nil err
|
||||||
// with a nil error the message is acked.
|
|
||||||
AutoAck bool
|
AutoAck bool
|
||||||
// Subscribers with the same queue name
|
|
||||||
|
// Handler executed when errors occur processing messages
|
||||||
|
ErrorHandler Handler
|
||||||
|
|
||||||
|
// Subscribers with the same group name
|
||||||
// will create a shared subscription where each
|
// will create a shared subscription where each
|
||||||
// receives a subset of messages.
|
// receives a subset of messages.
|
||||||
Queue string
|
Group string
|
||||||
|
|
||||||
// Other options for implementations of the interface
|
// Other options for implementations of the interface
|
||||||
// can be stored in a context
|
// can be stored in a context
|
||||||
Context context.Context
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Option func
|
||||||
type Option func(*Options)
|
type Option func(*Options)
|
||||||
|
|
||||||
|
// PublishOption func
|
||||||
type PublishOption func(*PublishOptions)
|
type PublishOption func(*PublishOptions)
|
||||||
|
|
||||||
// PublishContext set context
|
// PublishContext sets the context
|
||||||
func PublishContext(ctx context.Context) PublishOption {
|
func PublishContext(ctx context.Context) PublishOption {
|
||||||
return func(o *PublishOptions) {
|
return func(o *PublishOptions) {
|
||||||
o.Context = ctx
|
o.Context = ctx
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SubscribeOption func
|
||||||
type SubscribeOption func(*SubscribeOptions)
|
type SubscribeOption func(*SubscribeOptions)
|
||||||
|
|
||||||
|
// NewSubscribeOptions creates new SubscribeOptions
|
||||||
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
|
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
|
||||||
opt := SubscribeOptions{
|
options := SubscribeOptions{
|
||||||
AutoAck: true,
|
AutoAck: true,
|
||||||
|
Context: context.Background(),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&opt)
|
o(&options)
|
||||||
}
|
}
|
||||||
|
|
||||||
return opt
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
// Addrs sets the host addresses to be used by the broker
|
// Addrs sets the host addresses to be used by the broker
|
||||||
@@ -85,14 +131,21 @@ func Codec(c codec.Marshaler) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DisableAutoAck will disable auto acking of messages
|
// DisableAutoAck disables auto ack
|
||||||
// after they have been handled.
|
|
||||||
func DisableAutoAck() SubscribeOption {
|
func DisableAutoAck() SubscribeOption {
|
||||||
return func(o *SubscribeOptions) {
|
return func(o *SubscribeOptions) {
|
||||||
o.AutoAck = false
|
o.AutoAck = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SubscribeAutoAck will disable auto acking of messages
|
||||||
|
// after they have been handled.
|
||||||
|
func SubscribeAutoAck(b bool) SubscribeOption {
|
||||||
|
return func(o *SubscribeOptions) {
|
||||||
|
o.AutoAck = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ErrorHandler will catch all broker errors that cant be handled
|
// ErrorHandler will catch all broker errors that cant be handled
|
||||||
// in normal way, for example Codec errors
|
// in normal way, for example Codec errors
|
||||||
func ErrorHandler(h Handler) Option {
|
func ErrorHandler(h Handler) Option {
|
||||||
@@ -101,13 +154,29 @@ func ErrorHandler(h Handler) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Queue sets the name of the queue to share messages on
|
// SubscribeErrorHandler will catch all broker errors that cant be handled
|
||||||
func Queue(name string) SubscribeOption {
|
// in normal way, for example Codec errors
|
||||||
|
func SubscribeErrorHandler(h Handler) SubscribeOption {
|
||||||
return func(o *SubscribeOptions) {
|
return func(o *SubscribeOptions) {
|
||||||
o.Queue = name
|
o.ErrorHandler = h
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Queue sets the subscribers sueue
|
||||||
|
func Queue(name string) SubscribeOption {
|
||||||
|
return func(o *SubscribeOptions) {
|
||||||
|
o.Group = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeGroup sets the name of the queue to share messages on
|
||||||
|
func SubscribeGroup(name string) SubscribeOption {
|
||||||
|
return func(o *SubscribeOptions) {
|
||||||
|
o.Group = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registry sets registry option
|
||||||
func Registry(r registry.Registry) Option {
|
func Registry(r registry.Registry) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Registry = r
|
o.Registry = r
|
||||||
@@ -121,13 +190,20 @@ func Secure(b bool) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Specify TLS Config
|
// TLSConfig sets the TLS Config
|
||||||
func TLSConfig(t *tls.Config) Option {
|
func TLSConfig(t *tls.Config) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.TLSConfig = t
|
o.TLSConfig = t
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Logger sets the logger
|
||||||
|
func Logger(l logger.Logger) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
o.Logger = l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SubscribeContext set context
|
// SubscribeContext set context
|
||||||
func SubscribeContext(ctx context.Context) SubscribeOption {
|
func SubscribeContext(ctx context.Context) SubscribeOption {
|
||||||
return func(o *SubscribeOptions) {
|
return func(o *SubscribeOptions) {
|
||||||
|
|||||||
32
build/build.go
Normal file
32
build/build.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// Package build is for building source into a package
|
||||||
|
package build
|
||||||
|
|
||||||
|
// Build is an interface for building packages
|
||||||
|
type Build interface {
|
||||||
|
// Package builds a package
|
||||||
|
Package(name string, src *Source) (*Package, error)
|
||||||
|
// Remove removes the package
|
||||||
|
Remove(*Package) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source is the source of a build
|
||||||
|
type Source struct {
|
||||||
|
// Path to the source if local
|
||||||
|
Path string
|
||||||
|
// Language is the language of code
|
||||||
|
Language string
|
||||||
|
// Location of the source
|
||||||
|
Repository string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Package is packaged format for source
|
||||||
|
type Package struct {
|
||||||
|
// Name of the package
|
||||||
|
Name string
|
||||||
|
// Location of the package
|
||||||
|
Path string
|
||||||
|
// Type of package e.g tarball, binary, docker
|
||||||
|
Type string
|
||||||
|
// Source of the package
|
||||||
|
Source *Source
|
||||||
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
package build
|
package build
|
||||||
|
|
||||||
|
// Options struct
|
||||||
type Options struct {
|
type Options struct {
|
||||||
// local path to download source
|
// local path to download source
|
||||||
Path string
|
Path string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Option func
|
||||||
type Option func(o *Options)
|
type Option func(o *Options)
|
||||||
|
|
||||||
// Local path for repository
|
// Path is the Local path for repository
|
||||||
func Path(p string) Option {
|
func Path(p string) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.Path = p
|
o.Path = p
|
||||||
29
cache/cache.go
vendored
29
cache/cache.go
vendored
@@ -1,29 +0,0 @@
|
|||||||
// Package cache is a caching interface
|
|
||||||
package cache
|
|
||||||
|
|
||||||
// Cache is an interface for caching
|
|
||||||
type Cache interface {
|
|
||||||
// Initialise options
|
|
||||||
Init(...Option) error
|
|
||||||
// Get a value
|
|
||||||
Get(key string) (interface{}, error)
|
|
||||||
// Set a value
|
|
||||||
Set(key string, val interface{}) error
|
|
||||||
// Delete a value
|
|
||||||
Delete(key string) error
|
|
||||||
// Name of the implementation
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
Nodes []string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
// Nodes sets the nodes for the cache
|
|
||||||
func Nodes(v ...string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Nodes = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
80
cache/memcache/memcache.go
vendored
80
cache/memcache/memcache.go
vendored
@@ -1,80 +0,0 @@
|
|||||||
// Package memcache is a memcache implementation of the Cache
|
|
||||||
package memcache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
|
|
||||||
"github.com/bradfitz/gomemcache/memcache"
|
|
||||||
"github.com/micro/go-micro/v3/cache"
|
|
||||||
)
|
|
||||||
|
|
||||||
type memcacheCache struct {
|
|
||||||
options cache.Options
|
|
||||||
client *memcache.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type memcacheItem struct {
|
|
||||||
Key string
|
|
||||||
Value interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memcacheCache) Init(opts ...cache.Option) error {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&m.options)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memcacheCache) Get(key string) (interface{}, error) {
|
|
||||||
item, err := m.client.Get(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var mc *memcacheItem
|
|
||||||
|
|
||||||
if err := json.Unmarshal(item.Value, &mc); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return mc.Value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memcacheCache) Set(key string, val interface{}) error {
|
|
||||||
b, err := json.Marshal(val)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return m.client.Set(&memcache.Item{
|
|
||||||
Key: key,
|
|
||||||
Value: b,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memcacheCache) Delete(key string) error {
|
|
||||||
return m.client.Delete(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memcacheCache) String() string {
|
|
||||||
return "memcache"
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewCache returns a new memcache Cache
|
|
||||||
func NewCache(opts ...cache.Option) cache.Cache {
|
|
||||||
var options cache.Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// get and set the nodes
|
|
||||||
nodes := options.Nodes
|
|
||||||
if len(nodes) == 0 {
|
|
||||||
nodes = []string{"localhost:11211"}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &memcacheCache{
|
|
||||||
options: options,
|
|
||||||
client: memcache.New(nodes...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
56
cache/memory/memory.go
vendored
56
cache/memory/memory.go
vendored
@@ -1,56 +0,0 @@
|
|||||||
// Package memory is an in memory cache
|
|
||||||
package memory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/cache"
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type memoryCache struct {
|
|
||||||
// TODO: use a decent caching library
|
|
||||||
sync.RWMutex
|
|
||||||
values map[string]interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryCache) Init(opts ...cache.Option) error {
|
|
||||||
// TODO: implement
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryCache) Get(key string) (interface{}, error) {
|
|
||||||
m.RLock()
|
|
||||||
defer m.RUnlock()
|
|
||||||
|
|
||||||
v, ok := m.values[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.NotFound("go.micro.cache", key+" not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryCache) Set(key string, val interface{}) error {
|
|
||||||
m.Lock()
|
|
||||||
m.values[key] = val
|
|
||||||
m.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryCache) Delete(key string) error {
|
|
||||||
m.Lock()
|
|
||||||
delete(m.values, key)
|
|
||||||
m.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memoryCache) String() string {
|
|
||||||
return "memory"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCache(opts ...cache.Option) cache.Cache {
|
|
||||||
return &memoryCache{
|
|
||||||
values: make(map[string]interface{}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,9 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/util/backoff"
|
"github.com/unistack-org/micro/v3/util/backoff"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// BackoffFunc is the backoff call func
|
||||||
type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error)
|
type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error)
|
||||||
|
|
||||||
func exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) {
|
func exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) {
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
package client
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"hash/fnv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
cache "github.com/patrickmn/go-cache"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewCache returns an initialised cache.
|
|
||||||
func NewCache() *Cache {
|
|
||||||
return &Cache{
|
|
||||||
cache: cache.New(cache.NoExpiration, 30*time.Second),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache for responses
|
|
||||||
type Cache struct {
|
|
||||||
cache *cache.Cache
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get a response from the cache
|
|
||||||
func (c *Cache) Get(ctx context.Context, req Request) (interface{}, bool) {
|
|
||||||
return c.cache.Get(key(ctx, req))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set a response in the cache
|
|
||||||
func (c *Cache) Set(ctx context.Context, req Request, rsp interface{}, expiry time.Duration) {
|
|
||||||
c.cache.Set(key(ctx, req), rsp, expiry)
|
|
||||||
}
|
|
||||||
|
|
||||||
// List the key value pairs in the cache
|
|
||||||
func (c *Cache) List() map[string]string {
|
|
||||||
items := c.cache.Items()
|
|
||||||
|
|
||||||
rsp := make(map[string]string, len(items))
|
|
||||||
for k, v := range items {
|
|
||||||
bytes, _ := json.Marshal(v.Object)
|
|
||||||
rsp[k] = string(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
return rsp
|
|
||||||
}
|
|
||||||
|
|
||||||
// key returns a hash for the context and request
|
|
||||||
func key(ctx context.Context, req Request) string {
|
|
||||||
ns, _ := metadata.Get(ctx, "Micro-Namespace")
|
|
||||||
|
|
||||||
bytes, _ := json.Marshal(map[string]interface{}{
|
|
||||||
"namespace": ns,
|
|
||||||
"request": map[string]interface{}{
|
|
||||||
"service": req.Service(),
|
|
||||||
"endpoint": req.Endpoint(),
|
|
||||||
"method": req.Method(),
|
|
||||||
"body": req.Body(),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
h := fnv.New64()
|
|
||||||
h.Write(bytes)
|
|
||||||
return fmt.Sprintf("%x", h.Sum(nil))
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package client
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCache(t *testing.T) {
|
|
||||||
ctx := context.TODO()
|
|
||||||
req := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"}
|
|
||||||
|
|
||||||
t.Run("CacheMiss", func(t *testing.T) {
|
|
||||||
if _, ok := NewCache().Get(ctx, req); ok {
|
|
||||||
t.Errorf("Expected to get no result from Get")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("CacheHit", func(t *testing.T) {
|
|
||||||
c := NewCache()
|
|
||||||
|
|
||||||
rsp := "theresponse"
|
|
||||||
c.Set(ctx, req, rsp, time.Minute)
|
|
||||||
|
|
||||||
if res, ok := c.Get(ctx, req); !ok {
|
|
||||||
t.Errorf("Expected a result, got nothing")
|
|
||||||
} else if res != rsp {
|
|
||||||
t.Errorf("Expected '%v' result, got '%v'", rsp, res)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCacheKey(t *testing.T) {
|
|
||||||
ctx := context.TODO()
|
|
||||||
|
|
||||||
req1 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"}
|
|
||||||
req2 := &testRequest{service: "go.micro.service.foo", method: "Foo.Baz"}
|
|
||||||
req3 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar", body: "customquery"}
|
|
||||||
|
|
||||||
t.Run("IdenticalRequests", func(t *testing.T) {
|
|
||||||
key1 := key(ctx, req1)
|
|
||||||
key2 := key(ctx, req1)
|
|
||||||
if key1 != key2 {
|
|
||||||
t.Errorf("Expected the keys to match for identical requests and context")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("DifferentRequestEndpoints", func(t *testing.T) {
|
|
||||||
key1 := key(ctx, req1)
|
|
||||||
key2 := key(ctx, req2)
|
|
||||||
|
|
||||||
if key1 == key2 {
|
|
||||||
t.Errorf("Expected the keys to differ for different request endpoints")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("DifferentRequestBody", func(t *testing.T) {
|
|
||||||
key1 := key(ctx, req2)
|
|
||||||
key2 := key(ctx, req3)
|
|
||||||
|
|
||||||
if key1 == key2 {
|
|
||||||
t.Errorf("Expected the keys to differ for different request bodies")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("DifferentMetadata", func(t *testing.T) {
|
|
||||||
mdCtx := metadata.Set(context.TODO(), "Micro-Namespace", "bar")
|
|
||||||
key1 := key(mdCtx, req1)
|
|
||||||
key2 := key(ctx, req1)
|
|
||||||
|
|
||||||
if key1 == key2 {
|
|
||||||
t.Errorf("Expected the keys to differ for different metadata")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/codec"
|
"github.com/unistack-org/micro/v3/codec"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// DefaultClient is the global default client
|
||||||
|
DefaultClient Client = NewClient()
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is the interface used to make requests to services.
|
// Client is the interface used to make requests to services.
|
||||||
|
|||||||
@@ -14,3 +14,13 @@ func FromContext(ctx context.Context) (Client, bool) {
|
|||||||
func NewContext(ctx context.Context, c Client) context.Context {
|
func NewContext(ctx context.Context, c Client) context.Context {
|
||||||
return context.WithValue(ctx, clientKey{}, c)
|
return context.WithValue(ctx, clientKey{}, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetPublishOption returns a function to setup a context with given value
|
||||||
|
func SetPublishOption(k, v interface{}) PublishOption {
|
||||||
|
return func(o *PublishOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
# GRPC Client
|
|
||||||
|
|
||||||
The grpc client is a [micro.Client](https://godoc.org/github.com/micro/go-micro/client#Client) compatible client.
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
The client makes use of the [google.golang.org/grpc](google.golang.org/grpc) framework for the underlying communication mechanism.
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
Specify the client to your micro service
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro"
|
|
||||||
"github.com/micro/go-plugins/client/grpc"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
service := micro.NewService(
|
|
||||||
micro.Name("greeter"),
|
|
||||||
micro.Client(grpc.NewClient()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -1,206 +0,0 @@
|
|||||||
package grpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
b "bytes"
|
|
||||||
|
|
||||||
"github.com/golang/protobuf/jsonpb"
|
|
||||||
"github.com/golang/protobuf/proto"
|
|
||||||
"github.com/micro/go-micro/v3/codec"
|
|
||||||
"github.com/micro/go-micro/v3/codec/bytes"
|
|
||||||
"github.com/oxtoacart/bpool"
|
|
||||||
"google.golang.org/grpc"
|
|
||||||
"google.golang.org/grpc/encoding"
|
|
||||||
)
|
|
||||||
|
|
||||||
type jsonCodec struct{}
|
|
||||||
type protoCodec struct{}
|
|
||||||
type bytesCodec struct{}
|
|
||||||
type wrapCodec struct{ encoding.Codec }
|
|
||||||
|
|
||||||
var jsonpbMarshaler = &jsonpb.Marshaler{}
|
|
||||||
var useNumber bool
|
|
||||||
|
|
||||||
// create buffer pool with 16 instances each preallocated with 256 bytes
|
|
||||||
var bufferPool = bpool.NewSizedBufferPool(16, 256)
|
|
||||||
|
|
||||||
var (
|
|
||||||
defaultGRPCCodecs = map[string]encoding.Codec{
|
|
||||||
"application/json": jsonCodec{},
|
|
||||||
"application/proto": protoCodec{},
|
|
||||||
"application/protobuf": protoCodec{},
|
|
||||||
"application/octet-stream": protoCodec{},
|
|
||||||
"application/grpc": protoCodec{},
|
|
||||||
"application/grpc+json": jsonCodec{},
|
|
||||||
"application/grpc+proto": protoCodec{},
|
|
||||||
"application/grpc+bytes": bytesCodec{},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// UseNumber fix unmarshal Number(8234567890123456789) to interface(8.234567890123457e+18)
|
|
||||||
func UseNumber() {
|
|
||||||
useNumber = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w wrapCodec) String() string {
|
|
||||||
return w.Codec.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w wrapCodec) Marshal(v interface{}) ([]byte, error) {
|
|
||||||
b, ok := v.(*bytes.Frame)
|
|
||||||
if ok {
|
|
||||||
return b.Data, nil
|
|
||||||
}
|
|
||||||
return w.Codec.Marshal(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w wrapCodec) Unmarshal(data []byte, v interface{}) error {
|
|
||||||
b, ok := v.(*bytes.Frame)
|
|
||||||
if ok {
|
|
||||||
b.Data = data
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return w.Codec.Unmarshal(data, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (protoCodec) Marshal(v interface{}) ([]byte, error) {
|
|
||||||
switch m := v.(type) {
|
|
||||||
case *bytes.Frame:
|
|
||||||
return m.Data, nil
|
|
||||||
case proto.Message:
|
|
||||||
return proto.Marshal(m)
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("failed to marshal: %v is not type of *bytes.Frame or proto.Message", v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (protoCodec) Unmarshal(data []byte, v interface{}) error {
|
|
||||||
m, ok := v.(proto.Message)
|
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("failed to unmarshal: %v is not type of proto.Message", v)
|
|
||||||
}
|
|
||||||
return proto.Unmarshal(data, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (protoCodec) Name() string {
|
|
||||||
return "proto"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (bytesCodec) Marshal(v interface{}) ([]byte, error) {
|
|
||||||
b, ok := v.(*[]byte)
|
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("failed to marshal: %v is not type of *[]byte", v)
|
|
||||||
}
|
|
||||||
return *b, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (bytesCodec) Unmarshal(data []byte, v interface{}) error {
|
|
||||||
b, ok := v.(*[]byte)
|
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("failed to unmarshal: %v is not type of *[]byte", v)
|
|
||||||
}
|
|
||||||
*b = data
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (bytesCodec) Name() string {
|
|
||||||
return "bytes"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (jsonCodec) Marshal(v interface{}) ([]byte, error) {
|
|
||||||
if b, ok := v.(*bytes.Frame); ok {
|
|
||||||
return b.Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if pb, ok := v.(proto.Message); ok {
|
|
||||||
buf := bufferPool.Get()
|
|
||||||
defer bufferPool.Put(buf)
|
|
||||||
if err := jsonpbMarshaler.Marshal(buf, pb); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return buf.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (jsonCodec) Unmarshal(data []byte, v interface{}) error {
|
|
||||||
if len(data) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if b, ok := v.(*bytes.Frame); ok {
|
|
||||||
b.Data = data
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if pb, ok := v.(proto.Message); ok {
|
|
||||||
return jsonpb.Unmarshal(b.NewReader(data), pb)
|
|
||||||
}
|
|
||||||
|
|
||||||
dec := json.NewDecoder(b.NewReader(data))
|
|
||||||
if useNumber {
|
|
||||||
dec.UseNumber()
|
|
||||||
}
|
|
||||||
return dec.Decode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (jsonCodec) Name() string {
|
|
||||||
return "json"
|
|
||||||
}
|
|
||||||
|
|
||||||
type grpcCodec struct {
|
|
||||||
// headers
|
|
||||||
id string
|
|
||||||
target string
|
|
||||||
method string
|
|
||||||
endpoint string
|
|
||||||
|
|
||||||
s grpc.ClientStream
|
|
||||||
c encoding.Codec
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
|
|
||||||
md, err := g.s.Header()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if m == nil {
|
|
||||||
m = new(codec.Message)
|
|
||||||
}
|
|
||||||
if m.Header == nil {
|
|
||||||
m.Header = make(map[string]string, len(md))
|
|
||||||
}
|
|
||||||
for k, v := range md {
|
|
||||||
m.Header[k] = strings.Join(v, ",")
|
|
||||||
}
|
|
||||||
m.Id = g.id
|
|
||||||
m.Target = g.target
|
|
||||||
m.Method = g.method
|
|
||||||
m.Endpoint = g.endpoint
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcCodec) ReadBody(v interface{}) error {
|
|
||||||
if f, ok := v.(*bytes.Frame); ok {
|
|
||||||
return g.s.RecvMsg(f)
|
|
||||||
}
|
|
||||||
return g.s.RecvMsg(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcCodec) Write(m *codec.Message, v interface{}) error {
|
|
||||||
// if we don't have a body
|
|
||||||
if v != nil {
|
|
||||||
return g.s.SendMsg(v)
|
|
||||||
}
|
|
||||||
// write the body using the framing codec
|
|
||||||
return g.s.SendMsg(&bytes.Frame{Data: m.Body})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcCodec) Close() error {
|
|
||||||
return g.s.CloseSend()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcCodec) String() string {
|
|
||||||
return g.c.Name()
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package grpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
|
||||||
|
|
||||||
func microError(err error) error {
|
|
||||||
// no error
|
|
||||||
switch err {
|
|
||||||
case nil:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if verr, ok := err.(*errors.Error); ok {
|
|
||||||
return verr
|
|
||||||
}
|
|
||||||
|
|
||||||
// grpc error
|
|
||||||
s, ok := status.FromError(err)
|
|
||||||
if !ok {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// return first error from details
|
|
||||||
if details := s.Details(); len(details) > 0 {
|
|
||||||
if verr, ok := details[0].(error); ok {
|
|
||||||
return microError(verr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// try to decode micro *errors.Error
|
|
||||||
if e := errors.Parse(s.Message()); e.Code > 0 {
|
|
||||||
return e // actually a micro error
|
|
||||||
}
|
|
||||||
|
|
||||||
// fallback
|
|
||||||
return errors.InternalServerError("go.micro.client", s.Message())
|
|
||||||
}
|
|
||||||
@@ -1,708 +0,0 @@
|
|||||||
// Package grpc provides a gRPC client
|
|
||||||
package grpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
raw "github.com/micro/go-micro/v3/codec/bytes"
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
|
|
||||||
"google.golang.org/grpc"
|
|
||||||
"google.golang.org/grpc/credentials"
|
|
||||||
"google.golang.org/grpc/encoding"
|
|
||||||
gmetadata "google.golang.org/grpc/metadata"
|
|
||||||
)
|
|
||||||
|
|
||||||
type grpcClient struct {
|
|
||||||
opts client.Options
|
|
||||||
pool *pool
|
|
||||||
once atomic.Value
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
encoding.RegisterCodec(wrapCodec{jsonCodec{}})
|
|
||||||
encoding.RegisterCodec(wrapCodec{protoCodec{}})
|
|
||||||
encoding.RegisterCodec(wrapCodec{bytesCodec{}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// secure returns the dial option for whether its a secure or insecure connection
|
|
||||||
func (g *grpcClient) secure(addr string) grpc.DialOption {
|
|
||||||
// first we check if theres'a tls config
|
|
||||||
if g.opts.Context != nil {
|
|
||||||
if v := g.opts.Context.Value(tlsAuth{}); v != nil {
|
|
||||||
tls := v.(*tls.Config)
|
|
||||||
creds := credentials.NewTLS(tls)
|
|
||||||
// return tls config if it exists
|
|
||||||
return grpc.WithTransportCredentials(creds)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// default config
|
|
||||||
tlsConfig := &tls.Config{}
|
|
||||||
defaultCreds := grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))
|
|
||||||
|
|
||||||
// check if the address is prepended with https
|
|
||||||
if strings.HasPrefix(addr, "https://") {
|
|
||||||
return defaultCreds
|
|
||||||
}
|
|
||||||
|
|
||||||
// if no port is specified or port is 443 default to tls
|
|
||||||
_, port, err := net.SplitHostPort(addr)
|
|
||||||
// assuming with no port its going to be secured
|
|
||||||
if port == "443" {
|
|
||||||
return defaultCreds
|
|
||||||
} else if err != nil && strings.Contains(err.Error(), "missing port in address") {
|
|
||||||
return defaultCreds
|
|
||||||
}
|
|
||||||
|
|
||||||
// other fallback to insecure
|
|
||||||
return grpc.WithInsecure()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
|
||||||
var header map[string]string
|
|
||||||
|
|
||||||
header = make(map[string]string)
|
|
||||||
if md, ok := metadata.FromContext(ctx); ok {
|
|
||||||
header = make(map[string]string, len(md))
|
|
||||||
for k, v := range md {
|
|
||||||
header[strings.ToLower(k)] = v
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
header = make(map[string]string)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set timeout in nanoseconds
|
|
||||||
header["timeout"] = fmt.Sprintf("%d", opts.RequestTimeout)
|
|
||||||
// set the content type for the request
|
|
||||||
header["x-content-type"] = req.ContentType()
|
|
||||||
|
|
||||||
md := gmetadata.New(header)
|
|
||||||
ctx = gmetadata.NewOutgoingContext(ctx, md)
|
|
||||||
|
|
||||||
cf, err := g.newGRPCCodec(req.ContentType())
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
maxRecvMsgSize := g.maxRecvMsgSizeValue()
|
|
||||||
maxSendMsgSize := g.maxSendMsgSizeValue()
|
|
||||||
|
|
||||||
var grr error
|
|
||||||
|
|
||||||
grpcDialOptions := []grpc.DialOption{
|
|
||||||
grpc.WithTimeout(opts.DialTimeout),
|
|
||||||
g.secure(node.Address),
|
|
||||||
grpc.WithDefaultCallOptions(
|
|
||||||
grpc.MaxCallRecvMsgSize(maxRecvMsgSize),
|
|
||||||
grpc.MaxCallSendMsgSize(maxSendMsgSize),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts := g.getGrpcDialOptions(); opts != nil {
|
|
||||||
grpcDialOptions = append(grpcDialOptions, opts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
cc, err := g.pool.getConn(node.Address, grpcDialOptions...)
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
// defer execution of release
|
|
||||||
g.pool.release(node.Address, cc, grr)
|
|
||||||
}()
|
|
||||||
|
|
||||||
ch := make(chan error, 1)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
grpcCallOptions := []grpc.CallOption{
|
|
||||||
grpc.ForceCodec(cf),
|
|
||||||
grpc.CallContentSubtype(cf.Name())}
|
|
||||||
if opts := g.getGrpcCallOptions(); opts != nil {
|
|
||||||
grpcCallOptions = append(grpcCallOptions, opts...)
|
|
||||||
}
|
|
||||||
err := cc.Invoke(ctx, methodToGRPC(req.Service(), req.Endpoint()), req.Body(), rsp, grpcCallOptions...)
|
|
||||||
ch <- microError(err)
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case err := <-ch:
|
|
||||||
grr = err
|
|
||||||
case <-ctx.Done():
|
|
||||||
grr = errors.Timeout("go.micro.client", "%v", ctx.Err())
|
|
||||||
}
|
|
||||||
|
|
||||||
return grr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
|
||||||
var header map[string]string
|
|
||||||
|
|
||||||
if md, ok := metadata.FromContext(ctx); ok {
|
|
||||||
header = make(map[string]string, len(md))
|
|
||||||
for k, v := range md {
|
|
||||||
header[k] = v
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
header = make(map[string]string)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set timeout in nanoseconds
|
|
||||||
if opts.StreamTimeout > time.Duration(0) {
|
|
||||||
header["timeout"] = fmt.Sprintf("%d", opts.StreamTimeout)
|
|
||||||
}
|
|
||||||
// set the content type for the request
|
|
||||||
header["x-content-type"] = req.ContentType()
|
|
||||||
|
|
||||||
md := gmetadata.New(header)
|
|
||||||
ctx = gmetadata.NewOutgoingContext(ctx, md)
|
|
||||||
|
|
||||||
cf, err := g.newGRPCCodec(req.ContentType())
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
var dialCtx context.Context
|
|
||||||
var cancel context.CancelFunc
|
|
||||||
if opts.DialTimeout >= 0 {
|
|
||||||
dialCtx, cancel = context.WithTimeout(ctx, opts.DialTimeout)
|
|
||||||
} else {
|
|
||||||
dialCtx, cancel = context.WithCancel(ctx)
|
|
||||||
}
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
wc := wrapCodec{cf}
|
|
||||||
|
|
||||||
grpcDialOptions := []grpc.DialOption{
|
|
||||||
grpc.WithTimeout(opts.DialTimeout),
|
|
||||||
g.secure(node.Address),
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts := g.getGrpcDialOptions(); opts != nil {
|
|
||||||
grpcDialOptions = append(grpcDialOptions, opts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
cc, err := grpc.DialContext(dialCtx, node.Address, grpcDialOptions...)
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
desc := &grpc.StreamDesc{
|
|
||||||
StreamName: req.Service() + req.Endpoint(),
|
|
||||||
ClientStreams: true,
|
|
||||||
ServerStreams: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
grpcCallOptions := []grpc.CallOption{
|
|
||||||
grpc.ForceCodec(wc),
|
|
||||||
grpc.CallContentSubtype(cf.Name()),
|
|
||||||
}
|
|
||||||
if opts := g.getGrpcCallOptions(); opts != nil {
|
|
||||||
grpcCallOptions = append(grpcCallOptions, opts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// create a new cancelling context
|
|
||||||
newCtx, cancel := context.WithCancel(ctx)
|
|
||||||
|
|
||||||
st, err := cc.NewStream(newCtx, desc, methodToGRPC(req.Service(), req.Endpoint()), grpcCallOptions...)
|
|
||||||
if err != nil {
|
|
||||||
// we need to cleanup as we dialled and created a context
|
|
||||||
// cancel the context
|
|
||||||
cancel()
|
|
||||||
// close the connection
|
|
||||||
cc.Close()
|
|
||||||
// now return the error
|
|
||||||
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error creating stream: %v", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
codec := &grpcCodec{
|
|
||||||
s: st,
|
|
||||||
c: wc,
|
|
||||||
}
|
|
||||||
|
|
||||||
// set request codec
|
|
||||||
if r, ok := req.(*grpcRequest); ok {
|
|
||||||
r.codec = codec
|
|
||||||
}
|
|
||||||
|
|
||||||
// setup the stream response
|
|
||||||
stream := &grpcStream{
|
|
||||||
context: ctx,
|
|
||||||
request: req,
|
|
||||||
response: &response{
|
|
||||||
conn: cc,
|
|
||||||
stream: st,
|
|
||||||
codec: cf,
|
|
||||||
gcodec: codec,
|
|
||||||
},
|
|
||||||
stream: st,
|
|
||||||
conn: cc,
|
|
||||||
cancel: cancel,
|
|
||||||
}
|
|
||||||
|
|
||||||
// set the stream as the response
|
|
||||||
val := reflect.ValueOf(rsp).Elem()
|
|
||||||
val.Set(reflect.ValueOf(stream).Elem())
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) poolMaxStreams() int {
|
|
||||||
if g.opts.Context == nil {
|
|
||||||
return DefaultPoolMaxStreams
|
|
||||||
}
|
|
||||||
v := g.opts.Context.Value(poolMaxStreams{})
|
|
||||||
if v == nil {
|
|
||||||
return DefaultPoolMaxStreams
|
|
||||||
}
|
|
||||||
return v.(int)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) poolMaxIdle() int {
|
|
||||||
if g.opts.Context == nil {
|
|
||||||
return DefaultPoolMaxIdle
|
|
||||||
}
|
|
||||||
v := g.opts.Context.Value(poolMaxIdle{})
|
|
||||||
if v == nil {
|
|
||||||
return DefaultPoolMaxIdle
|
|
||||||
}
|
|
||||||
return v.(int)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) maxRecvMsgSizeValue() int {
|
|
||||||
if g.opts.Context == nil {
|
|
||||||
return DefaultMaxRecvMsgSize
|
|
||||||
}
|
|
||||||
v := g.opts.Context.Value(maxRecvMsgSizeKey{})
|
|
||||||
if v == nil {
|
|
||||||
return DefaultMaxRecvMsgSize
|
|
||||||
}
|
|
||||||
return v.(int)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) maxSendMsgSizeValue() int {
|
|
||||||
if g.opts.Context == nil {
|
|
||||||
return DefaultMaxSendMsgSize
|
|
||||||
}
|
|
||||||
v := g.opts.Context.Value(maxSendMsgSizeKey{})
|
|
||||||
if v == nil {
|
|
||||||
return DefaultMaxSendMsgSize
|
|
||||||
}
|
|
||||||
return v.(int)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) newGRPCCodec(contentType string) (encoding.Codec, error) {
|
|
||||||
codecs := make(map[string]encoding.Codec)
|
|
||||||
if g.opts.Context != nil {
|
|
||||||
if v := g.opts.Context.Value(codecsKey{}); v != nil {
|
|
||||||
codecs = v.(map[string]encoding.Codec)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if c, ok := codecs[contentType]; ok {
|
|
||||||
return wrapCodec{c}, nil
|
|
||||||
}
|
|
||||||
if c, ok := defaultGRPCCodecs[contentType]; ok {
|
|
||||||
return wrapCodec{c}, nil
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) Init(opts ...client.Option) error {
|
|
||||||
size := g.opts.PoolSize
|
|
||||||
ttl := g.opts.PoolTTL
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&g.opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// update pool configuration if the options changed
|
|
||||||
if size != g.opts.PoolSize || ttl != g.opts.PoolTTL {
|
|
||||||
g.pool.Lock()
|
|
||||||
g.pool.size = g.opts.PoolSize
|
|
||||||
g.pool.ttl = int64(g.opts.PoolTTL.Seconds())
|
|
||||||
g.pool.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) Options() client.Options {
|
|
||||||
return g.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
|
|
||||||
return newGRPCEvent(topic, msg, g.opts.ContentType, opts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) NewRequest(service, method string, req interface{}, reqOpts ...client.RequestOption) client.Request {
|
|
||||||
return newGRPCRequest(service, method, req, g.opts.ContentType, reqOpts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
|
||||||
if req == nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", "req is nil")
|
|
||||||
} else if rsp == nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", "rsp is nil")
|
|
||||||
}
|
|
||||||
// make a copy of call opts
|
|
||||||
callOpts := g.opts.CallOptions
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(&callOpts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if we already have a deadline
|
|
||||||
d, ok := ctx.Deadline()
|
|
||||||
if !ok {
|
|
||||||
// no deadline so we create a new one
|
|
||||||
var cancel context.CancelFunc
|
|
||||||
ctx, cancel = context.WithTimeout(ctx, callOpts.RequestTimeout)
|
|
||||||
defer cancel()
|
|
||||||
} else {
|
|
||||||
// got a deadline so no need to setup context
|
|
||||||
// but we need to set the timeout we pass along
|
|
||||||
opt := client.WithRequestTimeout(time.Until(d))
|
|
||||||
opt(&callOpts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// should we noop right here?
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return errors.New("go.micro.client", fmt.Sprintf("%v", ctx.Err()), 408)
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
// make copy of call method
|
|
||||||
gcall := g.call
|
|
||||||
|
|
||||||
// wrap the call in reverse
|
|
||||||
for i := len(callOpts.CallWrappers); i > 0; i-- {
|
|
||||||
gcall = callOpts.CallWrappers[i-1](gcall)
|
|
||||||
}
|
|
||||||
|
|
||||||
// return errors.New("go.micro.client", "request timeout", 408)
|
|
||||||
call := func(i int) error {
|
|
||||||
// call backoff first. Someone may want an initial start delay
|
|
||||||
t, err := callOpts.Backoff(ctx, req, i)
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// only sleep if greater than 0
|
|
||||||
if t.Seconds() > 0 {
|
|
||||||
time.Sleep(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
// use the router passed as a call option, or fallback to the rpc clients router
|
|
||||||
if callOpts.Router == nil {
|
|
||||||
callOpts.Router = g.opts.Router
|
|
||||||
}
|
|
||||||
// use the selector passed as a call option, or fallback to the rpc clients selector
|
|
||||||
if callOpts.Selector == nil {
|
|
||||||
callOpts.Selector = g.opts.Selector
|
|
||||||
}
|
|
||||||
|
|
||||||
// lookup the route to send the reques to
|
|
||||||
route, err := client.LookupRoute(req, callOpts)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// pass a node to enable backwards compatability as changing the
|
|
||||||
// call func would be a breaking change.
|
|
||||||
// todo v3: change the call func to accept a route
|
|
||||||
node := ®istry.Node{Address: route.Address}
|
|
||||||
|
|
||||||
// make the call
|
|
||||||
err = gcall(ctx, node, req, rsp, callOpts)
|
|
||||||
|
|
||||||
// record the result of the call to inform future routing decisions
|
|
||||||
g.opts.Selector.Record(*route, err)
|
|
||||||
|
|
||||||
// try and transform the error to a go-micro error
|
|
||||||
if verr, ok := err.(*errors.Error); ok {
|
|
||||||
return verr
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan error, callOpts.Retries+1)
|
|
||||||
var gerr error
|
|
||||||
|
|
||||||
for i := 0; i <= callOpts.Retries; i++ {
|
|
||||||
go func(i int) {
|
|
||||||
ch <- call(i)
|
|
||||||
}(i)
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return errors.New("go.micro.client", fmt.Sprintf("%v", ctx.Err()), 408)
|
|
||||||
case err := <-ch:
|
|
||||||
// if the call succeeded lets bail early
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
retry, rerr := callOpts.Retry(ctx, req, i, err)
|
|
||||||
if rerr != nil {
|
|
||||||
return rerr
|
|
||||||
}
|
|
||||||
|
|
||||||
if !retry {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
gerr = err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return gerr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
|
||||||
// make a copy of call opts
|
|
||||||
callOpts := g.opts.CallOptions
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(&callOpts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// #200 - streams shouldn't have a request timeout set on the context
|
|
||||||
|
|
||||||
// should we noop right here?
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return nil, errors.New("go.micro.client", fmt.Sprintf("%v", ctx.Err()), 408)
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
// make a copy of stream
|
|
||||||
gstream := g.stream
|
|
||||||
|
|
||||||
// wrap the call in reverse
|
|
||||||
for i := len(callOpts.CallWrappers); i > 0; i-- {
|
|
||||||
gstream = callOpts.CallWrappers[i-1](gstream)
|
|
||||||
}
|
|
||||||
|
|
||||||
call := func(i int) (client.Stream, error) {
|
|
||||||
// call backoff first. Someone may want an initial start delay
|
|
||||||
t, err := callOpts.Backoff(ctx, req, i)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// only sleep if greater than 0
|
|
||||||
if t.Seconds() > 0 {
|
|
||||||
time.Sleep(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
// use the router passed as a call option, or fallback to the rpc clients router
|
|
||||||
if callOpts.Router == nil {
|
|
||||||
callOpts.Router = g.opts.Router
|
|
||||||
}
|
|
||||||
// use the selector passed as a call option, or fallback to the rpc clients selector
|
|
||||||
if callOpts.Selector == nil {
|
|
||||||
callOpts.Selector = g.opts.Selector
|
|
||||||
}
|
|
||||||
|
|
||||||
// lookup the route to send the reques to
|
|
||||||
route, err := client.LookupRoute(req, callOpts)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// pass a node to enable backwards compatability as changing the
|
|
||||||
// call func would be a breaking change.
|
|
||||||
// todo v3: change the call func to accept a route
|
|
||||||
node := ®istry.Node{Address: route.Address}
|
|
||||||
|
|
||||||
// make the call
|
|
||||||
stream := &grpcStream{}
|
|
||||||
err = g.stream(ctx, node, req, stream, callOpts)
|
|
||||||
|
|
||||||
// record the result of the call to inform future routing decisions
|
|
||||||
g.opts.Selector.Record(*route, err)
|
|
||||||
|
|
||||||
// try and transform the error to a go-micro error
|
|
||||||
if verr, ok := err.(*errors.Error); ok {
|
|
||||||
return nil, verr
|
|
||||||
}
|
|
||||||
|
|
||||||
g.opts.Selector.Record(*route, err)
|
|
||||||
return stream, err
|
|
||||||
}
|
|
||||||
|
|
||||||
type response struct {
|
|
||||||
stream client.Stream
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan response, callOpts.Retries+1)
|
|
||||||
var grr error
|
|
||||||
|
|
||||||
for i := 0; i <= callOpts.Retries; i++ {
|
|
||||||
go func(i int) {
|
|
||||||
s, err := call(i)
|
|
||||||
ch <- response{s, err}
|
|
||||||
}(i)
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return nil, errors.New("go.micro.client", fmt.Sprintf("%v", ctx.Err()), 408)
|
|
||||||
case rsp := <-ch:
|
|
||||||
// if the call succeeded lets bail early
|
|
||||||
if rsp.err == nil {
|
|
||||||
return rsp.stream, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
retry, rerr := callOpts.Retry(ctx, req, i, grr)
|
|
||||||
if rerr != nil {
|
|
||||||
return nil, rerr
|
|
||||||
}
|
|
||||||
|
|
||||||
if !retry {
|
|
||||||
return nil, rsp.err
|
|
||||||
}
|
|
||||||
|
|
||||||
grr = rsp.err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, grr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
|
||||||
var options client.PublishOptions
|
|
||||||
var body []byte
|
|
||||||
|
|
||||||
// fail early on connect error
|
|
||||||
if !g.once.Load().(bool) {
|
|
||||||
if err := g.opts.Broker.Connect(); err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
g.once.Store(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(map[string]string)
|
|
||||||
}
|
|
||||||
md["Content-Type"] = p.ContentType()
|
|
||||||
md["Micro-Topic"] = p.Topic()
|
|
||||||
|
|
||||||
// passed in raw data
|
|
||||||
if d, ok := p.Payload().(*raw.Frame); ok {
|
|
||||||
body = d.Data
|
|
||||||
} else {
|
|
||||||
// use codec for payload
|
|
||||||
cf, err := g.newGRPCCodec(p.ContentType())
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
// set the body
|
|
||||||
b, err := cf.Marshal(p.Payload())
|
|
||||||
if err != nil {
|
|
||||||
return errors.InternalServerError("go.micro.client", err.Error())
|
|
||||||
}
|
|
||||||
body = b
|
|
||||||
}
|
|
||||||
|
|
||||||
topic := p.Topic()
|
|
||||||
|
|
||||||
// get the exchange
|
|
||||||
if len(options.Exchange) > 0 {
|
|
||||||
topic = options.Exchange
|
|
||||||
}
|
|
||||||
|
|
||||||
return g.opts.Broker.Publish(topic, &broker.Message{
|
|
||||||
Header: md,
|
|
||||||
Body: body,
|
|
||||||
}, broker.PublishContext(options.Context))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) String() string {
|
|
||||||
return "grpc"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) getGrpcDialOptions() []grpc.DialOption {
|
|
||||||
if g.opts.CallOptions.Context == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
v := g.opts.CallOptions.Context.Value(grpcDialOptions{})
|
|
||||||
|
|
||||||
if v == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
opts, ok := v.([]grpc.DialOption)
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *grpcClient) getGrpcCallOptions() []grpc.CallOption {
|
|
||||||
if g.opts.CallOptions.Context == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
v := g.opts.CallOptions.Context.Value(grpcCallOptions{})
|
|
||||||
|
|
||||||
if v == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
opts, ok := v.([]grpc.CallOption)
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func newClient(opts ...client.Option) client.Client {
|
|
||||||
options := client.NewOptions()
|
|
||||||
// default content type for grpc
|
|
||||||
options.ContentType = "application/grpc+proto"
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
rc := &grpcClient{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
rc.once.Store(false)
|
|
||||||
|
|
||||||
rc.pool = newPool(options.PoolSize, options.PoolTTL, rc.poolMaxIdle(), rc.poolMaxStreams())
|
|
||||||
|
|
||||||
c := client.Client(rc)
|
|
||||||
|
|
||||||
// wrap in reverse
|
|
||||||
for i := len(options.Wrappers); i > 0; i-- {
|
|
||||||
c = options.Wrappers[i-1](c)
|
|
||||||
}
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewClient(opts ...client.Option) client.Client {
|
|
||||||
return newClient(opts...)
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user