Compare commits
	
		
			332 Commits
		
	
	
		
			v2.8.0
			...
			v3.0.0-gam
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | ||
|  | 563768b58a | ||
|  | 9dfeb98111 | ||
|  | 5f4491bb86 | ||
|  | fbdf1f2c1c | ||
|  | a3a7434f2c | ||
|  | 592179c0a2 | ||
|  | 9b74bc52d6 | ||
|  | 05f3e1a125 | ||
|  | 16c591d741 | ||
|  | 755b816086 | ||
|  | 7aa92fa8b5 | ||
|  | 5077683b70 | ||
|  | 7f6cefd9c9 | ||
|  | 647ce61dec | ||
|  | d3326efd4b | ||
|  | 6920677f1e | ||
|  | 1838e4a1ee | ||
|  | 96233b2d9b | ||
|  | e082ac42a0 | ||
|  | d7ef224447 | ||
|  | 8c6f4062ef | ||
|  | 0d860c53a6 | ||
| bcc890e47c | |||
|  | f9bf562393 | ||
| dfa50a888d | |||
|  | e63b9015ae | ||
| 3627e47f04 | |||
|  | 7d41c2224e | ||
|  | 68927e875b | ||
|  | 0c19a87c89 | ||
|  | f73ec65ac3 | ||
|  | b27e71ae64 | ||
|  | 0299517f0d | ||
|  | e1404a1100 | ||
|  | 057d61063f | ||
|  | 73a3f596e8 | ||
|  | 0287ab8751 | ||
|  | 42c28f2b6d | ||
|  | a2bb0bea2d | ||
|  | 9f9c748f9b | ||
|  | a5e9dc21ca | ||
|  | 3f4b58b58c | ||
|  | 0a79db498c | ||
|  | 7c5e3b0f30 | ||
|  | 07fbb06ed8 | ||
|  | a4252ba69c | ||
|  | 8fe4f1f2c3 | ||
|  | 2e04fcd718 | ||
|  | 7355455020 | ||
|  | 040577fb74 | ||
|  | 4e7621da18 | ||
|  | 8e30ede8c7 | ||
|  | 630ceb5dad | ||
|  | 85ae232936 | ||
|  | 13ea0eec02 | ||
|  | 09ec20fded | ||
|  | 3480e0a64e | ||
|  | 318a80f824 | ||
|  | 6d9a38a747 | ||
|  | 58d6726380 | ||
|  | e5db6ea8a7 | ||
|  | 3468331506 | ||
|  | 1bac08cc0e | ||
|  | 333320dcb8 | ||
|  | ce12c040fa | ||
|  | ee36e26edc | ||
|  | 3ffb899951 | ||
|  | 00bd2bc65f | ||
|  | 86f4235aaf | ||
|  | b37f9c94b8 | ||
|  | 0ed1c70d29 | ||
|  | db8e10834b | ||
|  | 0a937745cd | ||
|  | f5ed7e5833 | ||
|  | 859b9e7786 | ||
|  | 2b033b6495 | ||
|  | 51caf2a24e | ||
|  | eaa46c2de7 | ||
|  | 90dca65f55 | ||
| 97ae2979ad | |||
|  | 6f309dada3 | ||
|  | f99b436ec2 | ||
|  | c817f29d6e | ||
|  | f744c6248f | ||
|  | 4ff114e798 | ||
|  | c58ac35dfc | ||
|  | b5314829fa | ||
|  | 41c7688697 | ||
|  | b021546c09 | ||
|  | 6898a65508 | ||
|  | d577dd6abe | ||
|  | 3c633e3577 | ||
|  | 174e44b846 | ||
|  | a63480a81a | ||
|  | 6d9d94b105 | ||
|  | 64e9185386 | ||
|  | 1b5c83f3cc | ||
|  | 979af853b9 | ||
|  | a64078b5c3 | ||
|  | 58845d7012 | ||
|  | dcf01ebbf0 | ||
|  | 355ad2a1af | ||
|  | b882ff3df9 | ||
|  | 6337c92cd0 | ||
|  | a95accad56 | ||
|  | 6532b6208b | ||
|  | 0f5c53b6e4 | ||
|  | deea8fecf4 | ||
|  | df3e5364ca | ||
|  | 132c1e35fe | ||
|  | 5967a68e78 | ||
|  | 104b7d8f8d | ||
|  | 4f0f4326df | ||
|  | ee02511658 | ||
|  | a8fc5590a8 | ||
|  | bc60f23ff6 | ||
|  | 2000da6fd8 | ||
|  | 5ab475636a | ||
|  | 51b4ab0abc | ||
|  | 687a5e2e58 | ||
|  | fcd307d902 | ||
|  | 00cd07a3a6 | ||
|  | a2a1f4dfbd | ||
|  | 2b506b1a2a | ||
|  | a2550820d3 | ||
|  | c940961574 | ||
|  | 695cc9d526 | ||
|  | 87543b2c8a | ||
|  | 5f9c3a6efd | ||
|  | 2b889087bd | ||
|  | ece02a6d21 | ||
|  | 58c6bbbf6b | ||
|  | c16f4b741c | ||
|  | 83cecdb294 | ||
|  | 8c7c27c573 | ||
|  | 5fd36d6cc0 | ||
|  | 3b40fde68b | ||
|  | 9d3365c4be | ||
|  | 2efb459c66 | ||
|  | 6add74b4f6 | ||
|  | c67d78f1ef | ||
|  | a89610ffea | ||
|  | da9bb11240 | ||
|  | a3a1a84172 | ||
|  | 1179d7e89a | ||
|  | a5df913926 | ||
|  | 9ce706191b | ||
|  | 0327f30e3c | ||
|  | 0ce132eb8f | ||
|  | 00b76e0a64 | ||
|  | aec27be9b4 | ||
|  | 86dfcb819b | ||
|  | d613804b0a | ||
| 92e9d05432 | |||
|  | 8dfd93e915 | ||
|  | e5136332e3 | ||
|  | f10fd4b479 | ||
|  | 74368026a5 | ||
|  | fde1aa9d6a | ||
|  | f45cdba9ba | ||
|  | 73c2f25935 | ||
|  | b270860b79 | ||
|  | 8e81cea96f | ||
|  | cdd8f9fd82 | ||
|  | e7ba930236 | ||
|  | a346064eaf | ||
|  | 47bdd5c993 | ||
|  | 9af12ff9df | ||
| 6c7bcf3883 | |||
|  | bbc3b7040b | ||
|  | 582f2e8b94 | ||
|  | bd3ef67328 | ||
|  | 1ccd4cd940 | ||
|  | aa679f7a73 | ||
|  | 003731ace9 | ||
|  | 7b379bf1f1 | ||
|  | b6f3e8b715 | ||
|  | 8f6ec21b91 | ||
|  | e4e56b0f3f | ||
|  | 219d29f664 | ||
|  | 8fb138af06 | 
							
								
								
									
										3
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,3 +0,0 @@ | |||||||
| # These are supported funding model platforms |  | ||||||
|  |  | ||||||
| github: asim |  | ||||||
							
								
								
									
										9
									
								
								.github/PULL_REQUEST_TEMPLATE.md
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								.github/PULL_REQUEST_TEMPLATE.md
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,9 @@ | |||||||
|  | ## Pull Request template | ||||||
|  | Please, go through these steps before clicking submit on this PR. | ||||||
|  |  | ||||||
|  | 1. Give a descriptive title to your PR. | ||||||
|  | 2. Provide a description of your changes. | ||||||
|  | 3. Make sure you have some relevant tests. | ||||||
|  | 4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if applicable). | ||||||
|  |  | ||||||
|  | **PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING** | ||||||
							
								
								
									
										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 | ||||||
							
								
								
									
										46
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										46
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,46 @@ | |||||||
|  | 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: checkout | ||||||
|  |       uses: actions/checkout@v2 | ||||||
|  |     - name: cache | ||||||
|  |       uses: actions/cache@v2 | ||||||
|  |       with: | ||||||
|  |         path: ~/go/pkg/mod | ||||||
|  |         key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} | ||||||
|  |         restore-keys: ${{ runner.os }}-go- | ||||||
|  |     - name: deps | ||||||
|  |       run: go get -v -t -d ./... | ||||||
|  |     - name: test | ||||||
|  |       env: | ||||||
|  |         INTEGRATION_TESTS: yes | ||||||
|  |       run: go test -mod readonly -v ./... | ||||||
|  |   lint: | ||||||
|  |     name: lint | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |       - name: checkout | ||||||
|  |         uses: actions/checkout@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 | ||||||
							
								
								
									
										21
									
								
								.github/workflows/docker.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										21
									
								
								.github/workflows/docker.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,21 +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 }} |  | ||||||
							
								
								
									
										60
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										60
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,28 +1,46 @@ | |||||||
| 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: checkout | ||||||
|  |  | ||||||
|     - name: Check out code into the Go module directory |  | ||||||
|       uses: actions/checkout@v2 |       uses: actions/checkout@v2 | ||||||
|  |     - name: cache | ||||||
|     - name: Get dependencies |       uses: actions/cache@v2 | ||||||
|       run: | |       with: | ||||||
|         go get -v -t -d ./... |         path: ~/go/pkg/mod | ||||||
|  |         key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} | ||||||
|     - name: Run tests |         restore-keys: ${{ runner.os }}-go- | ||||||
|       id: tests |     - name: deps | ||||||
|  |       run: go get -v -t -d ./... | ||||||
|  |     - name: test | ||||||
|       env: |       env: | ||||||
|         IN_TRAVIS_CI: yes |         INTEGRATION_TESTS: yes | ||||||
|       run: go test -v ./... |       run: 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 | ||||||
|   | |||||||
							
								
								
									
										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. | ||||||
|   | |||||||
							
								
								
									
										47
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										47
									
								
								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) <a href="https://slack.micro.mu"><img src="https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen" alt="Slack Widget"></a> | # 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) | ||||||
|  |  | ||||||
| Go Micro is a framework 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,42 +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 | ||||||
|  |  | ||||||
| To make use of Go Micro | To be created. | ||||||
|  |  | ||||||
| ```golang |  | ||||||
| import "github.com/micro/go-micro/v2" |  | ||||||
|  |  | ||||||
| // create a new service |  | ||||||
| service := micro.NewService( |  | ||||||
|     micro.Name("helloworld"), |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // initialise flags |  | ||||||
| service.Init() |  | ||||||
|  |  | ||||||
| // start the service |  | ||||||
| service.Run() |  | ||||||
| ``` |  | ||||||
|  |  | ||||||
| See the [docs](https://dev.micro.mu) for detailed information on the architecture, installation and use of go-micro. |  | ||||||
|  |  | ||||||
| ## 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 ( |  | ||||||
| 	// Commmands 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,96 +0,0 @@ | |||||||
| package discord |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"errors" |  | ||||||
| 	"strings" |  | ||||||
| 	"sync" |  | ||||||
|  |  | ||||||
| 	"github.com/bwmarrin/discordgo" |  | ||||||
| 	"github.com/micro/go-micro/v2/agent/input" |  | ||||||
| 	"github.com/micro/go-micro/v2/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 (dc *discordConn) Send(e *input.Event) error { |  | ||||||
| 	fields := strings.Split(e.To, ":") |  | ||||||
| 	_, err := dc.master.session.ChannelMessageSend(fields[0], string(e.Data)) |  | ||||||
| 	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/v2/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/v2/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/v2/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/v2/agent/input" |  | ||||||
| 	"github.com/micro/go-micro/v2/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/v2/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/v2/api" |  | ||||||
| 	client "github.com/micro/go-micro/v2/client" |  | ||||||
| 	server "github.com/micro/go-micro/v2/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/v2/registry" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| 	"github.com/micro/go-micro/v2/server" | 	"github.com/unistack-org/micro/v3/server" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Api interface { | type Api interface { | ||||||
| @@ -18,7 +18,7 @@ type Api interface { | |||||||
| 	Register(*Endpoint) error | 	Register(*Endpoint) error | ||||||
| 	// Register a route | 	// Register a route | ||||||
| 	Deregister(*Endpoint) error | 	Deregister(*Endpoint) error | ||||||
| 	// Implemenation of api | 	// Implementation of api | ||||||
| 	String() string | 	String() string | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,13 +4,13 @@ package api | |||||||
| import ( | import ( | ||||||
| 	"net/http" | 	"net/http" | ||||||
|  |  | ||||||
| 	goapi "github.com/micro/go-micro/v2/api" | 	goapi "github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" | 	"github.com/unistack-org/micro/v3/api/handler" | ||||||
| 	api "github.com/micro/go-micro/v2/api/proto" | 	api "github.com/unistack-org/micro/v3/api/proto" | ||||||
| 	"github.com/micro/go-micro/v2/client" | 	"github.com/unistack-org/micro/v3/client" | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" | 	"github.com/unistack-org/micro/v3/errors" | ||||||
| 	"github.com/micro/go-micro/v2/errors" | 	"github.com/unistack-org/micro/v3/util/ctx" | ||||||
| 	"github.com/micro/go-micro/v2/util/ctx" | 	"github.com/unistack-org/micro/v3/util/router" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type apiHandler struct { | type apiHandler struct { | ||||||
| @@ -71,10 +71,8 @@ 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) | ||||||
| 	// create strategy |  | ||||||
| 	so := selector.WithStrategy(strategy(service.Services)) |  | ||||||
|  |  | ||||||
| 	if err := c.Call(cx, req, rsp, client.WithSelectOption(so)); 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,10 +7,8 @@ import ( | |||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	api "github.com/micro/go-micro/v2/api/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry" |  | ||||||
| 	"github.com/oxtoacart/bpool" | 	"github.com/oxtoacart/bpool" | ||||||
|  | 	api "github.com/unistack-org/micro/v3/api/proto" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var ( | var ( | ||||||
| @@ -109,11 +107,3 @@ func requestToProto(r *http.Request) (*api.Request, error) { | |||||||
|  |  | ||||||
| 	return req, nil | 	return req, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| // strategy is a hack for selection |  | ||||||
| func strategy(services []*registry.Service) selector.Strategy { |  | ||||||
| 	return func(_ []*registry.Service) selector.Next { |  | ||||||
| 		// ignore input to this function, use services above |  | ||||||
| 		return selector.Random(services) |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|   | |||||||
| @@ -11,10 +11,10 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/google/uuid" | 	"github.com/google/uuid" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" |  | ||||||
| 	proto "github.com/micro/go-micro/v2/api/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/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 ( | ||||||
|   | |||||||
| @@ -4,13 +4,14 @@ package http | |||||||
| import ( | import ( | ||||||
| 	"errors" | 	"errors" | ||||||
| 	"fmt" | 	"fmt" | ||||||
|  | 	"math/rand" | ||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"net/http/httputil" | 	"net/http/httputil" | ||||||
| 	"net/url" | 	"net/url" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" | 	"github.com/unistack-org/micro/v3/api/handler" | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| const ( | const ( | ||||||
| @@ -20,7 +21,7 @@ const ( | |||||||
| type httpHandler struct { | type httpHandler struct { | ||||||
| 	options handler.Options | 	options handler.Options | ||||||
|  |  | ||||||
| 	// set with different initialiser | 	// set with different initializer | ||||||
| 	s *api.Service | 	s *api.Service | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -64,16 +65,20 @@ func (h *httpHandler) getService(r *http.Request) (string, error) { | |||||||
| 		return "", errors.New("no route found") | 		return "", errors.New("no route found") | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// create a random selector | 	if len(service.Services) == 0 { | ||||||
| 	next := selector.Random(service.Services) | 		return "", errors.New("no route found") | ||||||
|  |  | ||||||
| 	// get the next node |  | ||||||
| 	s, err := next() |  | ||||||
| 	if err != nil { |  | ||||||
| 		return "", nil |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return fmt.Sprintf("http://%s", s.Address), nil | 	// get the nodes for this service | ||||||
|  | 	nodes := make([]*registry.Node, 0, len(service.Services)) | ||||||
|  | 	for _, srv := range service.Services { | ||||||
|  | 		nodes = append(nodes, srv.Nodes...) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// select a random node | ||||||
|  | 	node := nodes[rand.Int()%len(nodes)] | ||||||
|  |  | ||||||
|  | 	return fmt.Sprintf("http://%s", node.Address), nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (h *httpHandler) String() string { | func (h *httpHandler) String() string { | ||||||
|   | |||||||
| @@ -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/v2/api/handler" | 	"github.com/unistack-org/micro/v3/api/handler" | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver/vpath" | 	"github.com/unistack-org/micro/v3/api/resolver/vpath" | ||||||
| 	"github.com/micro/go-micro/v2/api/router" | 	"github.com/unistack-org/micro/v3/api/router" | ||||||
| 	regRouter "github.com/micro/go-micro/v2/api/router/registry" | 	regRouter "github.com/unistack-org/micro/v3/api/router/registry" | ||||||
| 	"github.com/micro/go-micro/v2/registry" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| 	"github.com/micro/go-micro/v2/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) { | ||||||
| @@ -58,7 +60,7 @@ func testHttp(t *testing.T, path, service, ns string) { | |||||||
| 		router.WithHandler("http"), | 		router.WithHandler("http"), | ||||||
| 		router.WithRegistry(r), | 		router.WithRegistry(r), | ||||||
| 		router.WithResolver(vpath.NewResolver( | 		router.WithResolver(vpath.NewResolver( | ||||||
| 			resolver.WithNamespace(resolver.StaticNamespace(ns)), | 			resolver.WithServicePrefix(ns), | ||||||
| 		)), | 		)), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,9 +1,8 @@ | |||||||
| package handler | package handler | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"github.com/micro/go-micro/v2/api/router" | 	"github.com/unistack-org/micro/v3/api/router" | ||||||
| 	"github.com/micro/go-micro/v2/client" | 	"github.com/unistack-org/micro/v3/client" | ||||||
| 	"github.com/micro/go-micro/v2/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) | ||||||
| @@ -62,7 +57,7 @@ func WithClient(c client.Client) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // WithmaxRecvSize specifies max body size | // WithMaxRecvSize specifies max body size | ||||||
| func WithMaxRecvSize(size int64) Option { | func WithMaxRecvSize(size int64) Option { | ||||||
| 	return func(o *Options) { | 	return func(o *Options) { | ||||||
| 		o.MaxRecvSize = size | 		o.MaxRecvSize = size | ||||||
|   | |||||||
| @@ -5,26 +5,24 @@ import ( | |||||||
| 	"encoding/json" | 	"encoding/json" | ||||||
| 	"io" | 	"io" | ||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"net/textproto" |  | ||||||
| 	"strconv" | 	"strconv" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	jsonpatch "github.com/evanphx/json-patch/v5" | 	jsonpatch "github.com/evanphx/json-patch/v5" | ||||||
| 	"github.com/micro/go-micro/v2/api" |  | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" |  | ||||||
| 	"github.com/micro/go-micro/v2/api/internal/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/client" |  | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" |  | ||||||
| 	"github.com/micro/go-micro/v2/codec" |  | ||||||
| 	"github.com/micro/go-micro/v2/codec/jsonrpc" |  | ||||||
| 	"github.com/micro/go-micro/v2/codec/protorpc" |  | ||||||
| 	"github.com/micro/go-micro/v2/errors" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| 	"github.com/micro/go-micro/v2/metadata" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry" |  | ||||||
| 	"github.com/micro/go-micro/v2/util/ctx" |  | ||||||
| 	"github.com/micro/go-micro/v2/util/qson" |  | ||||||
| 	"github.com/oxtoacart/bpool" | 	"github.com/oxtoacart/bpool" | ||||||
|  | 	"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/codec/jsonrpc" | ||||||
|  | 	"github.com/unistack-org/micro/v3/codec/protorpc" | ||||||
|  | 	"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 ( | ||||||
| @@ -65,14 +63,6 @@ func (b *buffer) Write(_ []byte) (int, error) { | |||||||
| 	return 0, nil | 	return 0, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| // strategy is a hack for selection |  | ||||||
| func strategy(services []*registry.Service) selector.Strategy { |  | ||||||
| 	return func(_ []*registry.Service) selector.Next { |  | ||||||
| 		// ignore input to this function, use services above |  | ||||||
| 		return selector.Random(services) |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||||||
| 	bsize := handler.DefaultMaxRecvSize | 	bsize := handler.DefaultMaxRecvSize | ||||||
| 	if h.opts.MaxRecvSize > 0 { | 	if h.opts.MaxRecvSize > 0 { | ||||||
| @@ -113,36 +103,17 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |||||||
|  |  | ||||||
| 	// create context | 	// create context | ||||||
| 	cx := ctx.FromRequest(r) | 	cx := ctx.FromRequest(r) | ||||||
| 	// get context from http handler wrappers |  | ||||||
| 	md, ok := metadata.FromContext(r.Context()) |  | ||||||
| 	if !ok { |  | ||||||
| 		md = make(metadata.Metadata) |  | ||||||
| 	} |  | ||||||
| 	// fill contex with http headers |  | ||||||
| 	md["Host"] = r.Host |  | ||||||
| 	md["Method"] = r.Method |  | ||||||
| 	// get canonical headers |  | ||||||
| 	for k, _ := range r.Header { |  | ||||||
| 		// may be need to get all values for key like r.Header.Values() provide in go 1.14 |  | ||||||
| 		md[textproto.CanonicalMIMEHeaderKey(k)] = r.Header.Get(k) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	// merge context with overwrite |  | ||||||
| 	cx = metadata.MergeContext(cx, md, true) |  | ||||||
|  |  | ||||||
| 	// set merged context to request | 	// set merged context to request | ||||||
| 	*r = *r.Clone(cx) | 	*r = *r.Clone(cx) | ||||||
| 	// if stream we currently only support json | 	// if stream we currently only support json | ||||||
| 	if isStream(r, service) { | 	if isStream(r, service) { | ||||||
| 		// drop older context as it can have timeouts and create new |  | ||||||
| 		//		md, _ := metadata.FromContext(cx) |  | ||||||
| 		//serveWebsocket(context.TODO(), w, r, service, c) |  | ||||||
| 		serveWebsocket(cx, w, r, service, c) | 		serveWebsocket(cx, w, r, service, c) | ||||||
| 		return | 		return | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// create strategy | 	// create custom router | ||||||
| 	so := selector.WithStrategy(strategy(service.Services)) | 	callOpt := client.WithRouter(router.New(service.Services)) | ||||||
|  |  | ||||||
| 	// walk the standard call path | 	// walk the standard call path | ||||||
| 	// get payload | 	// get payload | ||||||
| @@ -174,7 +145,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |||||||
| 		) | 		) | ||||||
|  |  | ||||||
| 		// make the call | 		// make the call | ||||||
| 		if err := c.Call(cx, req, response, client.WithSelectOption(so)); err != nil { | 		if err := c.Call(cx, req, response, callOpt); err != nil { | ||||||
| 			writeError(w, r, err) | 			writeError(w, r, err) | ||||||
| 			return | 			return | ||||||
| 		} | 		} | ||||||
| @@ -209,7 +180,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |||||||
| 			client.WithContentType(ct), | 			client.WithContentType(ct), | ||||||
| 		) | 		) | ||||||
| 		// make the call | 		// make the call | ||||||
| 		if err := c.Call(cx, req, &response, client.WithSelectOption(so)); err != nil { | 		if err := c.Call(cx, req, &response, callOpt); err != nil { | ||||||
| 			writeError(w, r, err) | 			writeError(w, r, err) | ||||||
| 			return | 			return | ||||||
| 		} | 		} | ||||||
| @@ -294,7 +265,7 @@ func requestPayload(r *http.Request) ([]byte, error) { | |||||||
|  |  | ||||||
| 	// otherwise as per usual | 	// otherwise as per usual | ||||||
| 	ctx := r.Context() | 	ctx := r.Context() | ||||||
| 	// dont user meadata.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 = make(map[string]string) | ||||||
|   | |||||||
| @@ -7,7 +7,7 @@ import ( | |||||||
| 	"testing" | 	"testing" | ||||||
|  |  | ||||||
| 	"github.com/golang/protobuf/proto" | 	"github.com/golang/protobuf/proto" | ||||||
| 	go_api "github.com/micro/go-micro/v2/api/proto" | 	go_api "github.com/unistack-org/micro/v3/api/proto" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func TestRequestPayloadFromRequest(t *testing.T) { | func TestRequestPayloadFromRequest(t *testing.T) { | ||||||
|   | |||||||
| @@ -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/v2/api" | 	raw "github.com/unistack-org/micro-codec-bytes" | ||||||
| 	"github.com/micro/go-micro/v2/client" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" | 	"github.com/unistack-org/micro/v3/client" | ||||||
| 	raw "github.com/micro/go-micro/v2/codec/bytes" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"github.com/micro/go-micro/v2/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 | ||||||
| @@ -110,9 +110,11 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request, | |||||||
| 		client.StreamingRequest(), | 		client.StreamingRequest(), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	so := selector.WithStrategy(strategy(service.Services)) | 	// create custom router | ||||||
|  | 	callOpt := client.WithRouter(router.New(service.Services)) | ||||||
|  |  | ||||||
| 	// create a new stream | 	// create a new stream | ||||||
| 	stream, err := c.Stream(ctx, req, client.WithSelectOption(so)) | 	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.DefaultLogger) { | ||||||
| 			logger.Error(err) | 			logger.Error(err) | ||||||
| @@ -185,7 +187,11 @@ func writeLoop(rw io.ReadWriter, stream client.Stream) { | |||||||
| 			if err != nil { | 			if err != nil { | ||||||
| 				if wserr, ok := err.(wsutil.ClosedError); ok { | 				if wserr, ok := err.(wsutil.ClosedError); ok { | ||||||
| 					switch wserr.Code { | 					switch wserr.Code { | ||||||
|  | 					case ws.StatusGoingAway: | ||||||
|  | 						// this happens when user leave the page | ||||||
|  | 						return | ||||||
| 					case ws.StatusNormalClosure, ws.StatusNoStatusRcvd: | 					case ws.StatusNormalClosure, ws.StatusNoStatusRcvd: | ||||||
|  | 						// this happens when user close ws connection, or we don't get any status | ||||||
| 						return | 						return | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
|   | |||||||
| @@ -5,15 +5,16 @@ import ( | |||||||
| 	"errors" | 	"errors" | ||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"io" | 	"io" | ||||||
|  | 	"math/rand" | ||||||
| 	"net" | 	"net" | ||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"net/http/httputil" | 	"net/http/httputil" | ||||||
| 	"net/url" | 	"net/url" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" | 	"github.com/unistack-org/micro/v3/api/handler" | ||||||
| 	"github.com/micro/go-micro/v2/client/selector" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| const ( | const ( | ||||||
| @@ -70,16 +71,20 @@ func (wh *webHandler) getService(r *http.Request) (string, error) { | |||||||
| 		return "", errors.New("no route found") | 		return "", errors.New("no route found") | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// create a random selector | 	// get the nodes | ||||||
| 	next := selector.Random(service.Services) | 	nodes := make([]*registry.Node, 0, len(service.Services)) | ||||||
|  | 	for _, srv := range service.Services { | ||||||
| 	// get the next node | 		nodes = append(nodes, srv.Nodes...) | ||||||
| 	s, err := next() |  | ||||||
| 	if err != nil { |  | ||||||
| 		return "", nil |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return fmt.Sprintf("http://%s", s.Address), nil | 	if len(nodes) == 0 { | ||||||
|  | 		return "", errors.New("no route found") | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// select a random node | ||||||
|  | 	node := nodes[rand.Int()%len(nodes)] | ||||||
|  |  | ||||||
|  | 	return fmt.Sprintf("http://%s", node.Address), nil | ||||||
| } | } | ||||||
|  |  | ||||||
| // serveWebSocket used to serve a web socket proxied connection | // serveWebSocket used to serve a web socket proxied connection | ||||||
|   | |||||||
| @@ -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,12 +6,17 @@ import ( | |||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Resolver struct{} | type Resolver struct { | ||||||
|  | 	opts resolver.Options | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { | ||||||
|  | 	// parse options | ||||||
|  | 	options := resolver.NewResolveOptions(opts...) | ||||||
|  |  | ||||||
| func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) { |  | ||||||
| 	// /foo.Bar/Service | 	// /foo.Bar/Service | ||||||
| 	if req.URL.Path == "/" { | 	if req.URL.Path == "/" { | ||||||
| 		return nil, errors.New("unknown name") | 		return nil, errors.New("unknown name") | ||||||
| @@ -26,6 +31,7 @@ func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) { | |||||||
| 		Host:   req.Host, | 		Host:   req.Host, | ||||||
| 		Method: req.Method, | 		Method: req.Method, | ||||||
| 		Path:   req.URL.Path, | 		Path:   req.URL.Path, | ||||||
|  | 		Domain: options.Domain, | ||||||
| 	}, nil | 	}, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -34,5 +40,5 @@ func (r *Resolver) String() string { | |||||||
| } | } | ||||||
|  |  | ||||||
| func NewResolver(opts ...resolver.Option) resolver.Resolver { | func NewResolver(opts ...resolver.Option) resolver.Resolver { | ||||||
| 	return &Resolver{} | 	return &Resolver{opts: resolver.NewOptions(opts...)} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -4,19 +4,23 @@ package host | |||||||
| import ( | import ( | ||||||
| 	"net/http" | 	"net/http" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Resolver struct { | type Resolver struct { | ||||||
| 	opts resolver.Options | 	opts resolver.Options | ||||||
| } | } | ||||||
|  |  | ||||||
| func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) { | func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { | ||||||
|  | 	// parse options | ||||||
|  | 	options := resolver.NewResolveOptions(opts...) | ||||||
|  |  | ||||||
| 	return &resolver.Endpoint{ | 	return &resolver.Endpoint{ | ||||||
| 		Name:   req.Host, | 		Name:   req.Host, | ||||||
| 		Host:   req.Host, | 		Host:   req.Host, | ||||||
| 		Method: req.Method, | 		Method: req.Method, | ||||||
| 		Path:   req.URL.Path, | 		Path:   req.URL.Path, | ||||||
|  | 		Domain: options.Domain, | ||||||
| 	}, nil | 	}, nil | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,23 +1,16 @@ | |||||||
| package resolver | package resolver | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"net/http" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // NewOptions returns new initialised options | type Options struct { | ||||||
| func NewOptions(opts ...Option) Options { | 	Handler       string | ||||||
| 	var options Options | 	ServicePrefix string | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if options.Namespace == nil { |  | ||||||
| 		options.Namespace = StaticNamespace("go.micro") |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return options |  | ||||||
| } | } | ||||||
|  |  | ||||||
|  | type Option func(o *Options) | ||||||
|  |  | ||||||
| // WithHandler sets the handler being used | // WithHandler sets the handler being used | ||||||
| func WithHandler(h string) Option { | func WithHandler(h string) Option { | ||||||
| 	return func(o *Options) { | 	return func(o *Options) { | ||||||
| @@ -25,9 +18,46 @@ func WithHandler(h string) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // WithNamespace sets the function which determines the namespace for a request | // WithServicePrefix sets the ServicePrefix option | ||||||
| func WithNamespace(n func(*http.Request) string) Option { | func WithServicePrefix(p string) Option { | ||||||
| 	return func(o *Options) { | 	return func(o *Options) { | ||||||
| 		o.Namespace = n | 		o.ServicePrefix = p | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // NewOptions returns new initialised options | ||||||
|  | func NewOptions(opts ...Option) Options { | ||||||
|  | 	var options Options | ||||||
|  | 	for _, o := range opts { | ||||||
|  | 		o(&options) | ||||||
|  | 	} | ||||||
|  | 	return options | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // ResolveOptions are used when resolving a request | ||||||
|  | type ResolveOptions struct { | ||||||
|  | 	Domain string | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // ResolveOption sets an option | ||||||
|  | type ResolveOption func(*ResolveOptions) | ||||||
|  |  | ||||||
|  | // Domain sets the resolve Domain option | ||||||
|  | func Domain(n string) ResolveOption { | ||||||
|  | 	return func(o *ResolveOptions) { | ||||||
|  | 		o.Domain = n | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // NewResolveOptions returns new initialised resolve options | ||||||
|  | func NewResolveOptions(opts ...ResolveOption) ResolveOptions { | ||||||
|  | 	var options ResolveOptions | ||||||
|  | 	for _, o := range opts { | ||||||
|  | 		o(&options) | ||||||
|  | 	} | ||||||
|  | 	if len(options.Domain) == 0 { | ||||||
|  | 		options.Domain = registry.DefaultDomain | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return options | ||||||
|  | } | ||||||
|   | |||||||
| @@ -5,26 +5,29 @@ import ( | |||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Resolver struct { | type Resolver struct { | ||||||
| 	opts resolver.Options | 	opts resolver.Options | ||||||
| } | } | ||||||
|  |  | ||||||
| func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) { | func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { | ||||||
|  | 	// parse options | ||||||
|  | 	options := resolver.NewResolveOptions(opts...) | ||||||
|  |  | ||||||
| 	if req.URL.Path == "/" { | 	if req.URL.Path == "/" { | ||||||
| 		return nil, resolver.ErrNotFound | 		return nil, resolver.ErrNotFound | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	parts := strings.Split(req.URL.Path[1:], "/") | 	parts := strings.Split(req.URL.Path[1:], "/") | ||||||
| 	ns := r.opts.Namespace(req) |  | ||||||
|  |  | ||||||
| 	return &resolver.Endpoint{ | 	return &resolver.Endpoint{ | ||||||
| 		Name:   ns + "." + parts[0], | 		Name:   r.opts.ServicePrefix + "." + parts[0], | ||||||
| 		Host:   req.Host, | 		Host:   req.Host, | ||||||
| 		Method: req.Method, | 		Method: req.Method, | ||||||
| 		Path:   req.URL.Path, | 		Path:   req.URL.Path, | ||||||
|  | 		Domain: options.Domain, | ||||||
| 	}, nil | 	}, nil | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -13,7 +13,7 @@ var ( | |||||||
|  |  | ||||||
| // Resolver resolves requests to endpoints | // Resolver resolves requests to endpoints | ||||||
| type Resolver interface { | type Resolver interface { | ||||||
| 	Resolve(r *http.Request) (*Endpoint, error) | 	Resolve(r *http.Request, opts ...ResolveOption) (*Endpoint, error) | ||||||
| 	String() string | 	String() string | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -27,18 +27,6 @@ type Endpoint struct { | |||||||
| 	Method string | 	Method string | ||||||
| 	// HTTP Path e.g /greeter. | 	// HTTP Path e.g /greeter. | ||||||
| 	Path string | 	Path string | ||||||
| } | 	// Domain endpoint exists within | ||||||
|  | 	Domain string | ||||||
| type Options struct { |  | ||||||
| 	Handler   string |  | ||||||
| 	Namespace func(*http.Request) string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Option func(o *Options) |  | ||||||
|  |  | ||||||
| // StaticNamespace returns the same namespace for each request |  | ||||||
| func StaticNamespace(ns string) func(*http.Request) string { |  | ||||||
| 	return func(*http.Request) string { |  | ||||||
| 		return ns |  | ||||||
| 	} |  | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										85
									
								
								api/resolver/subdomain/subdomain.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										85
									
								
								api/resolver/subdomain/subdomain.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,85 @@ | |||||||
|  | // Package subdomain is a resolver which uses the subdomain to determine the domain to route to. It | ||||||
|  | // offloads the endpoint resolution to a child resolver which is provided in New. | ||||||
|  | package subdomain | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"net" | ||||||
|  | 	"net/http" | ||||||
|  | 	"strings" | ||||||
|  |  | ||||||
|  | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
|  | 	"github.com/unistack-org/micro/v3/logger" | ||||||
|  | 	"golang.org/x/net/publicsuffix" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver { | ||||||
|  | 	options := resolver.NewOptions(opts...) | ||||||
|  | 	return &Resolver{options, parent} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type Resolver struct { | ||||||
|  | 	opts resolver.Options | ||||||
|  | 	resolver.Resolver | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { | ||||||
|  | 	if dom := r.Domain(req); len(dom) > 0 { | ||||||
|  | 		opts = append(opts, resolver.Domain(dom)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return r.Resolver.Resolve(req, opts...) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (r *Resolver) Domain(req *http.Request) string { | ||||||
|  | 	// determine the host, e.g. foobar.m3o.app | ||||||
|  | 	host := req.URL.Hostname() | ||||||
|  | 	if len(host) == 0 { | ||||||
|  | 		if h, _, err := net.SplitHostPort(req.Host); err == nil { | ||||||
|  | 			host = h // host does contain a port | ||||||
|  | 		} else if strings.Contains(err.Error(), "missing port in address") { | ||||||
|  | 			host = req.Host // host does not contain a port | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// check for an ip address | ||||||
|  | 	if net.ParseIP(host) != nil { | ||||||
|  | 		return "" | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// check for dev environment | ||||||
|  | 	if host == "localhost" || host == "127.0.0.1" { | ||||||
|  | 		return "" | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// extract the top level domain plus one (e.g. 'myapp.com') | ||||||
|  | 	domain, err := publicsuffix.EffectiveTLDPlusOne(host) | ||||||
|  | 	if err != nil { | ||||||
|  | 		logger.Debugf("Unable to extract domain from %v", host) | ||||||
|  | 		return "" | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// there was no subdomain | ||||||
|  | 	if host == domain { | ||||||
|  | 		return "" | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// remove the domain from the host, leaving the subdomain, e.g. "staging.foo.myapp.com" => "staging.foo" | ||||||
|  | 	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" | ||||||
|  | 	comps := strings.Split(subdomain, ".") | ||||||
|  | 	for i := len(comps)/2 - 1; i >= 0; i-- { | ||||||
|  | 		opp := len(comps) - 1 - i | ||||||
|  | 		comps[i], comps[opp] = comps[opp], comps[i] | ||||||
|  | 	} | ||||||
|  | 	return strings.Join(comps, "-") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (r *Resolver) String() string { | ||||||
|  | 	return "subdomain" | ||||||
|  | } | ||||||
							
								
								
									
										71
									
								
								api/resolver/subdomain/subdomain_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										71
									
								
								api/resolver/subdomain/subdomain_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,71 @@ | |||||||
|  | package subdomain | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"net/http" | ||||||
|  | 	"net/url" | ||||||
|  | 	"testing" | ||||||
|  |  | ||||||
|  | 	"github.com/unistack-org/micro/v3/api/resolver/vpath" | ||||||
|  |  | ||||||
|  | 	"github.com/stretchr/testify/assert" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func TestResolve(t *testing.T) { | ||||||
|  | 	tt := []struct { | ||||||
|  | 		Name   string | ||||||
|  | 		Host   string | ||||||
|  | 		Result string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Top level domain", | ||||||
|  | 			Host:   "micro.mu", | ||||||
|  | 			Result: "micro", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Effective top level domain", | ||||||
|  | 			Host:   "micro.com.au", | ||||||
|  | 			Result: "micro", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Subdomain dev", | ||||||
|  | 			Host:   "dev.micro.mu", | ||||||
|  | 			Result: "dev", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Subdomain foo", | ||||||
|  | 			Host:   "foo.micro.mu", | ||||||
|  | 			Result: "foo", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Multi-level subdomain", | ||||||
|  | 			Host:   "staging.myapp.m3o.app", | ||||||
|  | 			Result: "myapp-staging", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Dev host", | ||||||
|  | 			Host:   "127.0.0.1", | ||||||
|  | 			Result: "micro", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "Localhost", | ||||||
|  | 			Host:   "localhost", | ||||||
|  | 			Result: "micro", | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			Name:   "IP host", | ||||||
|  | 			Host:   "81.151.101.146", | ||||||
|  | 			Result: "micro", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tc := range tt { | ||||||
|  | 		t.Run(tc.Name, func(t *testing.T) { | ||||||
|  | 			r := NewResolver(vpath.NewResolver()) | ||||||
|  | 			result, err := r.Resolve(&http.Request{URL: &url.URL{Host: tc.Host, Path: "foo/bar"}}) | ||||||
|  | 			assert.Nil(t, err, "Expecter err to be nil") | ||||||
|  | 			if result != nil { | ||||||
|  | 				assert.Equal(t, tc.Result, result.Domain, "Expected %v but got %v", tc.Result, result.Domain) | ||||||
|  | 			} | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
| @@ -7,7 +7,7 @@ import ( | |||||||
| 	"regexp" | 	"regexp" | ||||||
| 	"strings" | 	"strings" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func NewResolver(opts ...resolver.Option) resolver.Resolver { | func NewResolver(opts ...resolver.Option) resolver.Resolver { | ||||||
| @@ -22,36 +22,41 @@ var ( | |||||||
| 	re = regexp.MustCompile("^v[0-9]+$") | 	re = regexp.MustCompile("^v[0-9]+$") | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) { | func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { | ||||||
| 	if req.URL.Path == "/" { | 	if req.URL.Path == "/" { | ||||||
| 		return nil, errors.New("unknown name") | 		return nil, errors.New("unknown name") | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	options := resolver.NewResolveOptions(opts...) | ||||||
|  |  | ||||||
| 	parts := strings.Split(req.URL.Path[1:], "/") | 	parts := strings.Split(req.URL.Path[1:], "/") | ||||||
| 	if len(parts) == 1 { | 	if len(parts) == 1 { | ||||||
| 		return &resolver.Endpoint{ | 		return &resolver.Endpoint{ | ||||||
| 			Name:   r.withNamespace(req, parts...), | 			Name:   r.withPrefix(parts...), | ||||||
| 			Host:   req.Host, | 			Host:   req.Host, | ||||||
| 			Method: req.Method, | 			Method: req.Method, | ||||||
| 			Path:   req.URL.Path, | 			Path:   req.URL.Path, | ||||||
|  | 			Domain: options.Domain, | ||||||
| 		}, nil | 		}, nil | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// /v1/foo | 	// /v1/foo | ||||||
| 	if re.MatchString(parts[0]) { | 	if re.MatchString(parts[0]) { | ||||||
| 		return &resolver.Endpoint{ | 		return &resolver.Endpoint{ | ||||||
| 			Name:   r.withNamespace(req, parts[0:2]...), | 			Name:   r.withPrefix(parts[0:2]...), | ||||||
| 			Host:   req.Host, | 			Host:   req.Host, | ||||||
| 			Method: req.Method, | 			Method: req.Method, | ||||||
| 			Path:   req.URL.Path, | 			Path:   req.URL.Path, | ||||||
|  | 			Domain: options.Domain, | ||||||
| 		}, nil | 		}, nil | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return &resolver.Endpoint{ | 	return &resolver.Endpoint{ | ||||||
| 		Name:   r.withNamespace(req, parts[0]), | 		Name:   r.withPrefix(parts[0]), | ||||||
| 		Host:   req.Host, | 		Host:   req.Host, | ||||||
| 		Method: req.Method, | 		Method: req.Method, | ||||||
| 		Path:   req.URL.Path, | 		Path:   req.URL.Path, | ||||||
|  | 		Domain: options.Domain, | ||||||
| 	}, nil | 	}, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -59,11 +64,12 @@ func (r *Resolver) String() string { | |||||||
| 	return "path" | 	return "path" | ||||||
| } | } | ||||||
|  |  | ||||||
| func (r *Resolver) withNamespace(req *http.Request, parts ...string) string { | // withPrefix transforms "foo" into "go.micro.api.foo" | ||||||
| 	ns := r.opts.Namespace(req) | func (r *Resolver) withPrefix(parts ...string) string { | ||||||
| 	if len(ns) == 0 { | 	p := r.opts.ServicePrefix | ||||||
| 		return strings.Join(parts, ".") | 	if len(p) > 0 { | ||||||
|  | 		parts = append([]string{p}, parts...) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return strings.Join(append([]string{ns}, parts...), ".") | 	return strings.Join(parts, ".") | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,9 +1,9 @@ | |||||||
| package router | package router | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver/vpath" | 	"github.com/unistack-org/micro/v3/api/resolver/vpath" | ||||||
| 	"github.com/micro/go-micro/v2/registry" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Options struct { | type Options struct { | ||||||
| @@ -16,8 +16,7 @@ type Option func(o *Options) | |||||||
|  |  | ||||||
| func NewOptions(opts ...Option) Options { | func NewOptions(opts ...Option) Options { | ||||||
| 	options := Options{ | 	options := Options{ | ||||||
| 		Handler:  "meta", | 		Handler: "meta", | ||||||
| 		Registry: registry.DefaultRegistry, |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
|   | |||||||
| @@ -10,13 +10,12 @@ import ( | |||||||
| 	"sync" | 	"sync" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/router" | 	"github.com/unistack-org/micro/v3/api/router" | ||||||
| 	"github.com/micro/go-micro/v2/api/router/util" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"github.com/micro/go-micro/v2/logger" | 	"github.com/unistack-org/micro/v3/metadata" | ||||||
| 	"github.com/micro/go-micro/v2/metadata" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| 	"github.com/micro/go-micro/v2/registry" | 	util "github.com/unistack-org/micro/v3/util/router" | ||||||
| 	"github.com/micro/go-micro/v2/registry/cache" |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // endpoint struct, that holds compiled pcre | // endpoint struct, that holds compiled pcre | ||||||
| @@ -31,9 +30,6 @@ type registryRouter struct { | |||||||
| 	exit chan bool | 	exit chan bool | ||||||
| 	opts router.Options | 	opts router.Options | ||||||
|  |  | ||||||
| 	// registry cache |  | ||||||
| 	rc cache.Cache |  | ||||||
|  |  | ||||||
| 	sync.RWMutex | 	sync.RWMutex | ||||||
| 	eps map[string]*api.Service | 	eps map[string]*api.Service | ||||||
| 	// compiled regexp for host and path | 	// compiled regexp for host and path | ||||||
| @@ -68,7 +64,7 @@ func (r *registryRouter) refresh() { | |||||||
|  |  | ||||||
| 		// for each service, get service and store endpoints | 		// for each service, get service and store endpoints | ||||||
| 		for _, s := range services { | 		for _, s := range services { | ||||||
| 			service, err := r.rc.GetService(s.Name) | 			service, err := r.opts.Registry.GetService(s.Name) | ||||||
| 			if err != nil { | 			if err != nil { | ||||||
| 				if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | 				if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | ||||||
| 					logger.Errorf("unable to get service: %v", err) | 					logger.Errorf("unable to get service: %v", err) | ||||||
| @@ -96,10 +92,10 @@ func (r *registryRouter) process(res *registry.Result) { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// get entry from cache | 	// get entry from cache | ||||||
| 	service, err := r.rc.GetService(res.Service.Name) | 	service, err := r.opts.Registry.GetService(res.Service.Name) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | 		if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | ||||||
| 			logger.Errorf("unable to get service: %v", err) | 			logger.Errorf("unable to get %v service: %v", res.Service.Name, err) | ||||||
| 		} | 		} | ||||||
| 		return | 		return | ||||||
| 	} | 	} | ||||||
| @@ -127,7 +123,10 @@ func (r *registryRouter) store(services []*registry.Service) { | |||||||
| 			key := fmt.Sprintf("%s.%s", service.Name, sep.Name) | 			key := fmt.Sprintf("%s.%s", service.Name, sep.Name) | ||||||
| 			// decode endpoint | 			// decode endpoint | ||||||
| 			end := api.Decode(sep.Metadata) | 			end := api.Decode(sep.Metadata) | ||||||
|  | 			// no endpoint or no name | ||||||
|  | 			if end == nil || len(end.Name) == 0 { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
| 			// if we got nothing skip | 			// if we got nothing skip | ||||||
| 			if err := api.Validate(end); err != nil { | 			if err := api.Validate(end); err != nil { | ||||||
| 				if logger.V(logger.TraceLevel, logger.DefaultLogger) { | 				if logger.V(logger.TraceLevel, logger.DefaultLogger) { | ||||||
| @@ -188,7 +187,7 @@ func (r *registryRouter) store(services []*registry.Service) { | |||||||
| 		for _, p := range ep.Endpoint.Path { | 		for _, p := range ep.Endpoint.Path { | ||||||
| 			var pcreok bool | 			var pcreok bool | ||||||
|  |  | ||||||
| 			if p[0] == '^' && p[len(p)-1] != '$' { | 			if p[0] == '^' && p[len(p)-1] == '$' { | ||||||
| 				pcrereg, err := regexp.CompilePOSIX(p) | 				pcrereg, err := regexp.CompilePOSIX(p) | ||||||
| 				if err == nil { | 				if err == nil { | ||||||
| 					cep.pcreregs = append(cep.pcreregs, pcrereg) | 					cep.pcreregs = append(cep.pcreregs, pcrereg) | ||||||
| @@ -260,7 +259,7 @@ func (r *registryRouter) watch() { | |||||||
| 			res, err := w.Next() | 			res, err := w.Next() | ||||||
| 			if err != nil { | 			if err != nil { | ||||||
| 				if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | 				if logger.V(logger.ErrorLevel, logger.DefaultLogger) { | ||||||
| 					logger.Errorf("error getting next endoint: %v", err) | 					logger.Errorf("error getting next endpoint: %v", err) | ||||||
| 				} | 				} | ||||||
| 				close(ch) | 				close(ch) | ||||||
| 				break | 				break | ||||||
| @@ -280,7 +279,6 @@ func (r *registryRouter) Close() error { | |||||||
| 		return nil | 		return nil | ||||||
| 	default: | 	default: | ||||||
| 		close(r.exit) | 		close(r.exit) | ||||||
| 		r.rc.Stop() |  | ||||||
| 	} | 	} | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
| @@ -434,7 +432,7 @@ func (r *registryRouter) Route(req *http.Request) (*api.Service, error) { | |||||||
| 	name := rp.Name | 	name := rp.Name | ||||||
|  |  | ||||||
| 	// get service | 	// get service | ||||||
| 	services, err := r.rc.GetService(name) | 	services, err := r.opts.Registry.GetService(name, registry.GetDomain(rp.Domain)) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
| @@ -478,21 +476,23 @@ func (r *registryRouter) Route(req *http.Request) (*api.Service, error) { | |||||||
| 	return nil, errors.New("unknown handler") | 	return nil, errors.New("unknown handler") | ||||||
| } | } | ||||||
|  |  | ||||||
| func newRouter(opts ...router.Option) *registryRouter { | func newRouter(opts ...router.Option) (*registryRouter, error) { | ||||||
| 	options := router.NewOptions(opts...) | 	options := router.NewOptions(opts...) | ||||||
|  | 	if options.Registry == nil { | ||||||
|  | 		return nil, fmt.Errorf("registry is not set") | ||||||
|  | 	} | ||||||
| 	r := ®istryRouter{ | 	r := ®istryRouter{ | ||||||
| 		exit: make(chan bool), | 		exit: make(chan bool), | ||||||
| 		opts: options, | 		opts: options, | ||||||
| 		rc:   cache.New(options.Registry), |  | ||||||
| 		eps:  make(map[string]*api.Service), | 		eps:  make(map[string]*api.Service), | ||||||
| 		ceps: make(map[string]*endpoint), | 		ceps: make(map[string]*endpoint), | ||||||
| 	} | 	} | ||||||
| 	go r.watch() | 	go r.watch() | ||||||
| 	go r.refresh() | 	go r.refresh() | ||||||
| 	return r | 	return r, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| // NewRouter returns the default router | // NewRouter returns the default router | ||||||
| func NewRouter(opts ...router.Option) router.Router { | func NewRouter(opts ...router.Option) (router.Router, error) { | ||||||
| 	return newRouter(opts...) | 	return newRouter(opts...) | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										38
									
								
								api/router/registry/registry_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										38
									
								
								api/router/registry/registry_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,38 @@ | |||||||
|  | package registry | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"testing" | ||||||
|  |  | ||||||
|  | 	"github.com/stretchr/testify/assert" | ||||||
|  | 	"github.com/unistack-org/micro/v3/registry" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func TestStoreRegex(t *testing.T) { | ||||||
|  | 	t.Skip() | ||||||
|  | 	router, err := newRouter() | ||||||
|  | 	if err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	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/v2/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,3 +1,5 @@ | |||||||
|  | // +build ignore | ||||||
|  |  | ||||||
| package router_test | package router_test | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| @@ -9,23 +11,26 @@ import ( | |||||||
| 	"testing" | 	"testing" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler" | 	"github.com/unistack-org/micro/v3/api/handler" | ||||||
| 	"github.com/micro/go-micro/v2/api/handler/rpc" | 	"github.com/unistack-org/micro/v3/api/handler/rpc" | ||||||
| 	"github.com/micro/go-micro/v2/api/router" | 	"github.com/unistack-org/micro/v3/api/router" | ||||||
| 	rregistry "github.com/micro/go-micro/v2/api/router/registry" | 	rregistry "github.com/unistack-org/micro/v3/api/router/registry" | ||||||
| 	rstatic "github.com/micro/go-micro/v2/api/router/static" | 	rstatic "github.com/unistack-org/micro/v3/api/router/static" | ||||||
| 	"github.com/micro/go-micro/v2/client" | 	"github.com/unistack-org/micro/v3/broker" | ||||||
| 	gcli "github.com/micro/go-micro/v2/client/grpc" | 	bmemory "github.com/unistack-org/micro/v3/broker/memory" | ||||||
| 	rmemory "github.com/micro/go-micro/v2/registry/memory" | 	"github.com/unistack-org/micro/v3/client" | ||||||
| 	"github.com/micro/go-micro/v2/server" | 	gcli "github.com/unistack-org/micro/v3/client/grpc" | ||||||
| 	gsrv "github.com/micro/go-micro/v2/server/grpc" | 	rmemory "github.com/unistack-org/micro/v3/registry/memory" | ||||||
| 	pb "github.com/micro/go-micro/v2/server/grpc/proto" | 	rt "github.com/unistack-org/micro/v3/router" | ||||||
|  | 	regRouter "github.com/unistack-org/micro/v3/router/registry" | ||||||
|  | 	"github.com/unistack-org/micro/v3/server" | ||||||
|  | 	gsrv "github.com/unistack-org/micro/v3/server/grpc" | ||||||
|  | 	pb "github.com/unistack-org/micro/v3/server/grpc/proto" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // server is used to implement helloworld.GreeterServer. | // server is used to implement helloworld.GreeterServer. | ||||||
| type testServer struct { | type testServer struct { | ||||||
| 	msgCount int |  | ||||||
| } | } | ||||||
|  |  | ||||||
| // TestHello implements helloworld.GreeterServer | // TestHello implements helloworld.GreeterServer | ||||||
| @@ -48,16 +53,23 @@ func (s *testServer) CallPcreInvalid(ctx context.Context, req *pb.Request, rsp * | |||||||
|  |  | ||||||
| func initial(t *testing.T) (server.Server, client.Client) { | func initial(t *testing.T) (server.Server, client.Client) { | ||||||
| 	r := rmemory.NewRegistry() | 	r := rmemory.NewRegistry() | ||||||
|  | 	b := bmemory.NewBroker(broker.Registry(r)) | ||||||
|  |  | ||||||
| 	// create a new client | 	// create a new client | ||||||
| 	s := gsrv.NewServer( | 	s := gsrv.NewServer( | ||||||
| 		server.Name("foo"), | 		server.Name("foo"), | ||||||
|  | 		server.Broker(b), | ||||||
| 		server.Registry(r), | 		server.Registry(r), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
|  | 	rtr := regRouter.NewRouter( | ||||||
|  | 		rt.Registry(r), | ||||||
|  | 	) | ||||||
|  |  | ||||||
| 	// create a new server | 	// create a new server | ||||||
| 	c := gcli.NewClient( | 	c := gcli.NewClient( | ||||||
| 		client.Registry(r), | 		client.Router(rtr), | ||||||
|  | 		client.Broker(b), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	h := &testServer{} | 	h := &testServer{} | ||||||
|   | |||||||
| @@ -8,13 +8,13 @@ import ( | |||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync" | 	"sync" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api" | 	"github.com/unistack-org/micro/v3/api" | ||||||
| 	"github.com/micro/go-micro/v2/api/router" | 	"github.com/unistack-org/micro/v3/api/router" | ||||||
| 	"github.com/micro/go-micro/v2/api/router/util" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"github.com/micro/go-micro/v2/logger" | 	"github.com/unistack-org/micro/v3/metadata" | ||||||
| 	"github.com/micro/go-micro/v2/metadata" | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| 	"github.com/micro/go-micro/v2/registry" | 	rutil "github.com/unistack-org/micro/v3/util/registry" | ||||||
| 	rutil "github.com/micro/go-micro/v2/util/registry" | 	util "github.com/unistack-org/micro/v3/util/router" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type endpoint struct { | type endpoint struct { | ||||||
|   | |||||||
| @@ -7,8 +7,8 @@ import ( | |||||||
| 	"net" | 	"net" | ||||||
| 	"os" | 	"os" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/server/acme" | 	"github.com/unistack-org/micro/v3/api/server/acme" | ||||||
| 	"github.com/micro/go-micro/v2/logger" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"golang.org/x/crypto/acme/autocert" | 	"golang.org/x/crypto/acme/autocert" | ||||||
| ) | ) | ||||||
|  |  | ||||||
|   | |||||||
| @@ -8,8 +8,8 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/caddyserver/certmagic" | 	"github.com/caddyserver/certmagic" | ||||||
| 	"github.com/micro/go-micro/v2/api/server/acme" | 	"github.com/unistack-org/micro/v3/api/server/acme" | ||||||
| 	"github.com/micro/go-micro/v2/logger" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type certmagicProvider struct { | type certmagicProvider struct { | ||||||
|   | |||||||
| @@ -10,8 +10,8 @@ import ( | |||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/caddyserver/certmagic" | 	"github.com/caddyserver/certmagic" | ||||||
| 	"github.com/micro/go-micro/v2/store" | 	"github.com/unistack-org/micro/v3/store" | ||||||
| 	"github.com/micro/go-micro/v2/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 | ||||||
|   | |||||||
| @@ -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,13 +5,10 @@ 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/v2/api/server" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"github.com/micro/go-micro/v2/api/server/cors" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type httpServer struct { | type httpServer struct { | ||||||
| @@ -58,14 +55,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) | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -97,7 +86,7 @@ func (s *httpServer) Start() error { | |||||||
| 	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) | 			logger.Error(err) | ||||||
| 		} | 		} | ||||||
| 	}() | 	}() | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,8 +4,8 @@ import ( | |||||||
| 	"crypto/tls" | 	"crypto/tls" | ||||||
| 	"net/http" | 	"net/http" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/api/resolver" | 	"github.com/unistack-org/micro/v3/api/resolver" | ||||||
| 	"github.com/micro/go-micro/v2/api/server/acme" | 	"github.com/unistack-org/micro/v3/api/server/acme" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Option func(o *Options) | type Option func(o *Options) | ||||||
| @@ -23,9 +23,9 @@ type Options struct { | |||||||
|  |  | ||||||
| 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...) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -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/v2/api" |  | ||||||
| 	client "github.com/micro/go-micro/v2/client" |  | ||||||
| 	server "github.com/micro/go-micro/v2/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 | ||||||
| 	// 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 | ||||||
|   | |||||||
| @@ -1,88 +0,0 @@ | |||||||
| package auth |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"github.com/google/uuid" |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/provider/basic" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| var ( |  | ||||||
| 	DefaultAuth = NewAuth() |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func NewAuth(opts ...Option) Auth { |  | ||||||
| 	options := Options{ |  | ||||||
| 		Provider: basic.NewProvider(), |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return &noop{ |  | ||||||
| 		opts: options, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type noop struct { |  | ||||||
| 	opts Options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // String returns the name of the implementation |  | ||||||
| func (n *noop) String() string { |  | ||||||
| 	return "noop" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Init the auth |  | ||||||
| func (n *noop) Init(opts ...Option) { |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&n.opts) |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Options set for auth |  | ||||||
| func (n *noop) Options() Options { |  | ||||||
| 	return n.opts |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Generate a new account |  | ||||||
| func (n *noop) 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().Namespace, |  | ||||||
| 	}, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Grant access to a resource |  | ||||||
| func (n *noop) Grant(rule *Rule) error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Revoke access to a resource |  | ||||||
| func (n *noop) Revoke(rule *Rule) error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Rules used to verify requests |  | ||||||
| func (n *noop) Rules(opts ...RulesOption) ([]*Rule, error) { |  | ||||||
| 	return []*Rule{}, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Verify an account has access to a resource |  | ||||||
| func (n *noop) Verify(acc *Account, res *Resource, opts ...VerifyOption) error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Inspect a token |  | ||||||
| func (n *noop) Inspect(token string) (*Account, error) { |  | ||||||
| 	return &Account{ID: uuid.New().String(), Issuer: n.Options().Namespace}, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Token generation using an account id and secret |  | ||||||
| func (n *noop) Token(opts ...TokenOption) (*Token, error) { |  | ||||||
| 	return &Token{}, nil |  | ||||||
| } |  | ||||||
| @@ -1,35 +1,35 @@ | |||||||
|  | // Package jwt is a jwt implementation of the auth interface | ||||||
| package jwt | package jwt | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"sync" | 	"sync" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/auth" | 	"github.com/unistack-org/micro/v3/auth" | ||||||
| 	"github.com/micro/go-micro/v2/auth/rules" | 	"github.com/unistack-org/micro/v3/util/token" | ||||||
| 	"github.com/micro/go-micro/v2/auth/token" | 	"github.com/unistack-org/micro/v3/util/token/jwt" | ||||||
| 	jwtToken "github.com/micro/go-micro/v2/auth/token/jwt" |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // NewAuth returns a new instance of the Auth service | // NewAuth returns a new instance of the Auth service | ||||||
| func NewAuth(opts ...auth.Option) auth.Auth { | func NewAuth(opts ...auth.Option) auth.Auth { | ||||||
| 	j := new(jwt) | 	j := new(jwtAuth) | ||||||
| 	j.Init(opts...) | 	j.Init(opts...) | ||||||
| 	return j | 	return j | ||||||
| } | } | ||||||
|  |  | ||||||
| type jwt struct { | type jwtAuth struct { | ||||||
| 	options auth.Options | 	options auth.Options | ||||||
| 	jwt     token.Provider | 	token   token.Provider | ||||||
| 	rules   []*auth.Rule | 	rules   []*auth.Rule | ||||||
|  |  | ||||||
| 	sync.Mutex | 	sync.Mutex | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) String() string { | func (j *jwtAuth) String() string { | ||||||
| 	return "jwt" | 	return "jwt" | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Init(opts ...auth.Option) { | func (j *jwtAuth) Init(opts ...auth.Option) { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
|  |  | ||||||
| @@ -37,31 +37,35 @@ func (j *jwt) Init(opts ...auth.Option) { | |||||||
| 		o(&j.options) | 		o(&j.options) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	j.jwt = jwtToken.NewTokenProvider( | 	j.token = jwt.NewTokenProvider( | ||||||
| 		token.WithPrivateKey(j.options.PrivateKey), | 		token.WithPrivateKey(j.options.PrivateKey), | ||||||
| 		token.WithPublicKey(j.options.PublicKey), | 		token.WithPublicKey(j.options.PublicKey), | ||||||
| 	) | 	) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Options() auth.Options { | func (j *jwtAuth) Options() auth.Options { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
| 	return j.options | 	return j.options | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { | func (j *jwtAuth) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { | ||||||
| 	options := auth.NewGenerateOptions(opts...) | 	options := auth.NewGenerateOptions(opts...) | ||||||
|  | 	if len(options.Issuer) == 0 { | ||||||
|  | 		options.Issuer = j.Options().Issuer | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	account := &auth.Account{ | 	account := &auth.Account{ | ||||||
| 		ID:       id, | 		ID:       id, | ||||||
| 		Type:     options.Type, | 		Type:     options.Type, | ||||||
| 		Scopes:   options.Scopes, | 		Scopes:   options.Scopes, | ||||||
| 		Metadata: options.Metadata, | 		Metadata: options.Metadata, | ||||||
| 		Issuer:   j.Options().Namespace, | 		Issuer:   options.Issuer, | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// generate a JWT secret which can be provided to the Token() method | 	// generate a JWT secret which can be provided to the Token() method | ||||||
| 	// and exchanged for an access token | 	// and exchanged for an access token | ||||||
| 	secret, err := j.jwt.Generate(account) | 	secret, err := j.token.Generate(account, token.WithExpiry(time.Hour*24*365)) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
| @@ -71,19 +75,19 @@ func (j *jwt) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, e | |||||||
| 	return account, nil | 	return account, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Grant(rule *auth.Rule) error { | func (j *jwtAuth) Grant(rule *auth.Rule) error { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
| 	j.rules = append(j.rules, rule) | 	j.rules = append(j.rules, rule) | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Revoke(rule *auth.Rule) error { | func (j *jwtAuth) Revoke(rule *auth.Rule) error { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
|  |  | ||||||
| 	rules := []*auth.Rule{} | 	rules := []*auth.Rule{} | ||||||
| 	for _, r := range rules { | 	for _, r := range j.rules { | ||||||
| 		if r.ID != rule.ID { | 		if r.ID != rule.ID { | ||||||
| 			rules = append(rules, r) | 			rules = append(rules, r) | ||||||
| 		} | 		} | ||||||
| @@ -93,7 +97,7 @@ func (j *jwt) Revoke(rule *auth.Rule) error { | |||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error { | func (j *jwtAuth) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
|  |  | ||||||
| @@ -102,20 +106,20 @@ func (j *jwt) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyO | |||||||
| 		o(&options) | 		o(&options) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return rules.Verify(j.rules, acc, res) | 	return auth.VerifyAccess(j.rules, acc, res) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) { | func (j *jwtAuth) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) { | ||||||
| 	j.Lock() | 	j.Lock() | ||||||
| 	defer j.Unlock() | 	defer j.Unlock() | ||||||
| 	return j.rules, nil | 	return j.rules, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Inspect(token string) (*auth.Account, error) { | func (j *jwtAuth) Inspect(token string) (*auth.Account, error) { | ||||||
| 	return j.jwt.Inspect(token) | 	return j.token.Inspect(token) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (j *jwt) Token(opts ...auth.TokenOption) (*auth.Token, error) { | func (j *jwtAuth) Token(opts ...auth.TokenOption) (*auth.Token, error) { | ||||||
| 	options := auth.NewTokenOptions(opts...) | 	options := auth.NewTokenOptions(opts...) | ||||||
|  |  | ||||||
| 	secret := options.RefreshToken | 	secret := options.RefreshToken | ||||||
| @@ -123,17 +127,17 @@ func (j *jwt) Token(opts ...auth.TokenOption) (*auth.Token, error) { | |||||||
| 		secret = options.Secret | 		secret = options.Secret | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	account, err := j.jwt.Inspect(secret) | 	account, err := j.token.Inspect(secret) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	access, err := j.jwt.Generate(account, token.WithExpiry(options.Expiry)) | 	access, err := j.token.Generate(account, token.WithExpiry(options.Expiry)) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	refresh, err := j.jwt.Generate(account, token.WithExpiry(options.Expiry+time.Hour)) | 	refresh, err := j.token.Generate(account, token.WithExpiry(options.Expiry+time.Hour)) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| 	} | 	} | ||||||
|   | |||||||
							
								
								
									
										81
									
								
								auth/noop/noop.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										81
									
								
								auth/noop/noop.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,81 @@ | |||||||
|  | package noop | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"github.com/google/uuid" | ||||||
|  | 	"github.com/unistack-org/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,9 +4,8 @@ import ( | |||||||
| 	"context" | 	"context" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/provider" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
| 	"github.com/micro/go-micro/v2/client" | 	"github.com/unistack-org/micro/v3/store" | ||||||
| 	"github.com/micro/go-micro/v2/store" |  | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func NewOptions(opts ...Option) Options { | func NewOptions(opts ...Option) Options { | ||||||
| @@ -14,16 +13,12 @@ func NewOptions(opts ...Option) Options { | |||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
| 		o(&options) | 		o(&options) | ||||||
| 	} | 	} | ||||||
| 	if options.Client == nil { |  | ||||||
| 		options.Client = client.DefaultClient |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return options | 	return options | ||||||
| } | } | ||||||
|  |  | ||||||
| type Options struct { | type Options struct { | ||||||
| 	// Namespace the service belongs to | 	// Issuer of the service's account | ||||||
| 	Namespace string | 	Issuer string | ||||||
| 	// ID is the services auth ID | 	// ID is the services auth ID | ||||||
| 	ID string | 	ID string | ||||||
| 	// Secret is used to authenticate the service | 	// Secret is used to authenticate the service | ||||||
| @@ -34,16 +29,16 @@ type Options struct { | |||||||
| 	PublicKey string | 	PublicKey string | ||||||
| 	// PrivateKey for encoding JWTs | 	// PrivateKey for encoding JWTs | ||||||
| 	PrivateKey string | 	PrivateKey string | ||||||
| 	// Provider is an auth provider |  | ||||||
| 	Provider provider.Provider |  | ||||||
| 	// LoginURL is the relative url path where a user can login | 	// LoginURL is the relative url path where a user can login | ||||||
| 	LoginURL string | 	LoginURL string | ||||||
| 	// Store to back auth | 	// Store to back auth | ||||||
| 	Store store.Store | 	Store store.Store | ||||||
| 	// Client to use for RPC |  | ||||||
| 	Client client.Client |  | ||||||
| 	// 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 context.Context | ||||||
| } | } | ||||||
|  |  | ||||||
| type Option func(o *Options) | type Option func(o *Options) | ||||||
| @@ -55,10 +50,10 @@ func Addrs(addrs ...string) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // Namespace the service belongs to | // Issuer of the services account | ||||||
| func Namespace(n string) Option { | func Issuer(i string) Option { | ||||||
| 	return func(o *Options) { | 	return func(o *Options) { | ||||||
| 		o.Namespace = n | 		o.Issuer = i | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -98,13 +93,6 @@ func ClientToken(token *Token) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // Provider set the auth provider |  | ||||||
| func Provider(p provider.Provider) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.Provider = p |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // LoginURL sets the auth LoginURL | // LoginURL sets the auth LoginURL | ||||||
| func LoginURL(url string) Option { | func LoginURL(url string) Option { | ||||||
| 	return func(o *Options) { | 	return func(o *Options) { | ||||||
| @@ -112,13 +100,6 @@ func LoginURL(url string) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // WithClient sets the client to use when making requests |  | ||||||
| func WithClient(c client.Client) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.Client = c |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type GenerateOptions struct { | type GenerateOptions struct { | ||||||
| 	// Metadata associated with the account | 	// Metadata associated with the account | ||||||
| 	Metadata map[string]string | 	Metadata map[string]string | ||||||
| @@ -130,6 +111,8 @@ type GenerateOptions struct { | |||||||
| 	Type string | 	Type string | ||||||
| 	// Secret used to authenticate the account | 	// Secret used to authenticate the account | ||||||
| 	Secret string | 	Secret string | ||||||
|  | 	// Issuer of the account, e.g. micro | ||||||
|  | 	Issuer string | ||||||
| } | } | ||||||
|  |  | ||||||
| type GenerateOption func(o *GenerateOptions) | type GenerateOption func(o *GenerateOptions) | ||||||
| @@ -169,6 +152,13 @@ func WithScopes(s ...string) GenerateOption { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // WithIssuer for the generated account | ||||||
|  | func WithIssuer(i string) GenerateOption { | ||||||
|  | 	return func(o *GenerateOptions) { | ||||||
|  | 		o.Issuer = i | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| // NewGenerateOptions from a slice of options | // NewGenerateOptions from a slice of options | ||||||
| func NewGenerateOptions(opts ...GenerateOption) GenerateOptions { | func NewGenerateOptions(opts ...GenerateOption) GenerateOptions { | ||||||
| 	var options GenerateOptions | 	var options GenerateOptions | ||||||
| @@ -187,6 +177,8 @@ type TokenOptions struct { | |||||||
| 	RefreshToken string | 	RefreshToken string | ||||||
| 	// Expiry is the time the token should live for | 	// Expiry is the time the token should live for | ||||||
| 	Expiry time.Duration | 	Expiry time.Duration | ||||||
|  | 	// Issuer of the account | ||||||
|  | 	Issuer string | ||||||
| } | } | ||||||
|  |  | ||||||
| type TokenOption func(o *TokenOptions) | type TokenOption func(o *TokenOptions) | ||||||
| @@ -211,6 +203,12 @@ func WithToken(rt string) TokenOption { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func WithTokenIssuer(iss string) TokenOption { | ||||||
|  | 	return func(o *TokenOptions) { | ||||||
|  | 		o.Issuer = iss | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| // NewTokenOptions from a slice of options | // NewTokenOptions from a slice of options | ||||||
| func NewTokenOptions(opts ...TokenOption) TokenOptions { | func NewTokenOptions(opts ...TokenOption) TokenOptions { | ||||||
| 	var options TokenOptions | 	var options TokenOptions | ||||||
| @@ -218,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 | ||||||
| 	} | 	} | ||||||
| @@ -227,7 +225,8 @@ func NewTokenOptions(opts ...TokenOption) TokenOptions { | |||||||
| } | } | ||||||
|  |  | ||||||
| type VerifyOptions struct { | type VerifyOptions struct { | ||||||
| 	Context context.Context | 	Context   context.Context | ||||||
|  | 	Namespace string | ||||||
| } | } | ||||||
|  |  | ||||||
| type VerifyOption func(o *VerifyOptions) | type VerifyOption func(o *VerifyOptions) | ||||||
| @@ -237,9 +236,15 @@ func VerifyContext(ctx context.Context) VerifyOption { | |||||||
| 		o.Context = ctx | 		o.Context = ctx | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  | func VerifyNamespace(ns string) VerifyOption { | ||||||
|  | 	return func(o *VerifyOptions) { | ||||||
|  | 		o.Namespace = ns | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| type RulesOptions struct { | type RulesOptions struct { | ||||||
| 	Context context.Context | 	Context   context.Context | ||||||
|  | 	Namespace string | ||||||
| } | } | ||||||
|  |  | ||||||
| type RulesOption func(o *RulesOptions) | type RulesOption func(o *RulesOptions) | ||||||
| @@ -249,3 +254,9 @@ func RulesContext(ctx context.Context) RulesOption { | |||||||
| 		o.Context = ctx | 		o.Context = ctx | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func RulesNamespace(ns string) RulesOption { | ||||||
|  | 	return func(o *RulesOptions) { | ||||||
|  | 		o.Namespace = ns | ||||||
|  | 	} | ||||||
|  | } | ||||||
|   | |||||||
| @@ -1,34 +0,0 @@ | |||||||
| package basic |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/provider" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // NewProvider returns an initialised basic provider |  | ||||||
| func NewProvider(opts ...provider.Option) provider.Provider { |  | ||||||
| 	var options provider.Options |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	return &basic{options} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type basic struct { |  | ||||||
| 	opts provider.Options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *basic) String() string { |  | ||||||
| 	return "basic" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *basic) Options() provider.Options { |  | ||||||
| 	return b.opts |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *basic) Endpoint(...provider.EndpointOption) string { |  | ||||||
| 	return "" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *basic) Redirect() string { |  | ||||||
| 	return "" |  | ||||||
| } |  | ||||||
| @@ -1,65 +0,0 @@ | |||||||
| package oauth |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"fmt" |  | ||||||
| 	"net/url" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/provider" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // NewProvider returns an initialised oauth provider |  | ||||||
| func NewProvider(opts ...provider.Option) provider.Provider { |  | ||||||
| 	var options provider.Options |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	return &oauth{options} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type oauth struct { |  | ||||||
| 	opts provider.Options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (o *oauth) String() string { |  | ||||||
| 	return "oauth" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (o *oauth) Options() provider.Options { |  | ||||||
| 	return o.opts |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (o *oauth) Endpoint(opts ...provider.EndpointOption) string { |  | ||||||
| 	var options provider.EndpointOptions |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	params := make(url.Values) |  | ||||||
| 	params.Add("response_type", "code") |  | ||||||
|  |  | ||||||
| 	if len(options.State) > 0 { |  | ||||||
| 		params.Add("state", options.State) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if len(options.LoginHint) > 0 { |  | ||||||
| 		params.Add("login_hint", options.LoginHint) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if clientID := o.opts.ClientID; len(clientID) > 0 { |  | ||||||
| 		params.Add("client_id", clientID) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if scope := o.opts.Scope; len(scope) > 0 { |  | ||||||
| 		params.Add("scope", scope) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if redir := o.Redirect(); len(redir) > 0 { |  | ||||||
| 		params.Add("redirect_uri", redir) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return fmt.Sprintf("%v?%v", o.opts.Endpoint, params.Encode()) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (o *oauth) Redirect() string { |  | ||||||
| 	return o.opts.Redirect |  | ||||||
| } |  | ||||||
| @@ -1,47 +0,0 @@ | |||||||
| package provider |  | ||||||
|  |  | ||||||
| // Option returns a function which sets an option |  | ||||||
| type Option func(*Options) |  | ||||||
|  |  | ||||||
| // Options a provider can have |  | ||||||
| type Options struct { |  | ||||||
| 	// ClientID is the application's ID. |  | ||||||
| 	ClientID string |  | ||||||
| 	// ClientSecret is the application's secret. |  | ||||||
| 	ClientSecret string |  | ||||||
| 	// Endpoint for the provider |  | ||||||
| 	Endpoint string |  | ||||||
| 	// Redirect url incase of UI |  | ||||||
| 	Redirect string |  | ||||||
| 	// Scope of the oauth request |  | ||||||
| 	Scope string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Credentials is an option which sets the client id and secret |  | ||||||
| func Credentials(id, secret string) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.ClientID = id |  | ||||||
| 		o.ClientSecret = secret |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Endpoint sets the endpoint option |  | ||||||
| func Endpoint(e string) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.Endpoint = e |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Redirect sets the Redirect option |  | ||||||
| func Redirect(r string) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.Redirect = r |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Scope sets the oauth scope |  | ||||||
| func Scope(s string) Option { |  | ||||||
| 	return func(o *Options) { |  | ||||||
| 		o.Scope = s |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
| @@ -1,49 +0,0 @@ | |||||||
| // Package provider is an external auth provider e.g oauth |  | ||||||
| package provider |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"time" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // Provider is an auth provider |  | ||||||
| type Provider interface { |  | ||||||
| 	// String returns the name of the provider |  | ||||||
| 	String() string |  | ||||||
| 	// Options returns the options of a provider |  | ||||||
| 	Options() Options |  | ||||||
| 	// Endpoint for the provider |  | ||||||
| 	Endpoint(...EndpointOption) string |  | ||||||
| 	// Redirect url incase of UI |  | ||||||
| 	Redirect() string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Grant is a granted authorisation |  | ||||||
| type Grant struct { |  | ||||||
| 	// token for reuse |  | ||||||
| 	Token string |  | ||||||
| 	// Expiry of the token |  | ||||||
| 	Expiry time.Time |  | ||||||
| 	// Scopes associated with grant |  | ||||||
| 	Scopes []string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type EndpointOptions struct { |  | ||||||
| 	// State is a code to verify the req |  | ||||||
| 	State string |  | ||||||
| 	// LoginHint prefils the user id on oauth clients |  | ||||||
| 	LoginHint string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type EndpointOption func(*EndpointOptions) |  | ||||||
|  |  | ||||||
| func WithState(c string) EndpointOption { |  | ||||||
| 	return func(o *EndpointOptions) { |  | ||||||
| 		o.State = c |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func WithLoginHint(hint string) EndpointOption { |  | ||||||
| 	return func(o *EndpointOptions) { |  | ||||||
| 		o.LoginHint = hint |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
| @@ -1,17 +1,15 @@ | |||||||
| package rules | package auth | ||||||
| 
 | 
 | ||||||
| import ( | import ( | ||||||
| 	"fmt" | 	"fmt" | ||||||
| 	"sort" | 	"sort" | ||||||
| 	"strings" | 	"strings" | ||||||
| 
 |  | ||||||
| 	"github.com/micro/go-micro/v2/auth" |  | ||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
| // Verify an account has access to a resource using the rules provided. If the account does not have | // VerifyAccess an account has access to a resource using the rules provided. If the account does not have | ||||||
| // access an error will be returned. If there are no rules provided which match the resource, an error | // access an error will be returned. If there are no rules provided which match the resource, an error | ||||||
| // will be returned | // will be returned | ||||||
| func Verify(rules []*auth.Rule, acc *auth.Account, res *auth.Resource) error { | func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error { | ||||||
| 	// the rule is only to be applied if the type matches the resource or is catch-all (*) | 	// the rule is only to be applied if the type matches the resource or is catch-all (*) | ||||||
| 	validTypes := []string{"*", res.Type} | 	validTypes := []string{"*", res.Type} | ||||||
| 
 | 
 | ||||||
| @@ -29,7 +27,7 @@ func Verify(rules []*auth.Rule, acc *auth.Account, res *auth.Resource) error { | |||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	// filter the rules to the ones which match the criteria above | 	// filter the rules to the ones which match the criteria above | ||||||
| 	filteredRules := make([]*auth.Rule, 0) | 	filteredRules := make([]*Rule, 0) | ||||||
| 	for _, rule := range rules { | 	for _, rule := range rules { | ||||||
| 		if !include(validTypes, rule.Resource.Type) { | 		if !include(validTypes, rule.Resource.Type) { | ||||||
| 			continue | 			continue | ||||||
| @@ -51,9 +49,9 @@ func Verify(rules []*auth.Rule, acc *auth.Account, res *auth.Resource) error { | |||||||
| 	// loop through the rules and check for a rule which applies to this account | 	// loop through the rules and check for a rule which applies to this account | ||||||
| 	for _, rule := range filteredRules { | 	for _, rule := range filteredRules { | ||||||
| 		// a blank scope indicates the rule applies to everyone, even nil accounts | 		// a blank scope indicates the rule applies to everyone, even nil accounts | ||||||
| 		if rule.Scope == auth.ScopePublic && rule.Access == auth.AccessDenied { | 		if rule.Scope == ScopePublic && rule.Access == AccessDenied { | ||||||
| 			return auth.ErrForbidden | 			return ErrForbidden | ||||||
| 		} else if rule.Scope == auth.ScopePublic && rule.Access == auth.AccessGranted { | 		} else if rule.Scope == ScopePublic && rule.Access == AccessGranted { | ||||||
| 			return nil | 			return nil | ||||||
| 		} | 		} | ||||||
| 
 | 
 | ||||||
| @@ -63,29 +61,29 @@ func Verify(rules []*auth.Rule, acc *auth.Account, res *auth.Resource) error { | |||||||
| 		} | 		} | ||||||
| 
 | 
 | ||||||
| 		// this rule applies to any account | 		// this rule applies to any account | ||||||
| 		if rule.Scope == auth.ScopeAccount && rule.Access == auth.AccessDenied { | 		if rule.Scope == ScopeAccount && rule.Access == AccessDenied { | ||||||
| 			return auth.ErrForbidden | 			return ErrForbidden | ||||||
| 		} else if rule.Scope == auth.ScopeAccount && rule.Access == auth.AccessGranted { | 		} else if rule.Scope == ScopeAccount && rule.Access == AccessGranted { | ||||||
| 			return nil | 			return nil | ||||||
| 		} | 		} | ||||||
| 
 | 
 | ||||||
| 		// if the account has the necessary scope | 		// if the account has the necessary scope | ||||||
| 		if include(acc.Scopes, rule.Scope) && rule.Access == auth.AccessDenied { | 		if include(acc.Scopes, rule.Scope) && rule.Access == AccessDenied { | ||||||
| 			return auth.ErrForbidden | 			return ErrForbidden | ||||||
| 		} else if include(acc.Scopes, rule.Scope) && rule.Access == auth.AccessGranted { | 		} else if include(acc.Scopes, rule.Scope) && rule.Access == AccessGranted { | ||||||
| 			return nil | 			return nil | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	// if no rules matched then return forbidden | 	// if no rules matched then return forbidden | ||||||
| 	return auth.ErrForbidden | 	return ErrForbidden | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| // include is a helper function which checks to see if the slice contains the value. includes is | // include is a helper function which checks to see if the slice contains the value. includes is | ||||||
| // 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 | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| @@ -1,25 +1,23 @@ | |||||||
| package rules | package auth | ||||||
| 
 | 
 | ||||||
| import ( | import ( | ||||||
| 	"testing" | 	"testing" | ||||||
| 
 |  | ||||||
| 	"github.com/micro/go-micro/v2/auth" |  | ||||||
| ) | ) | ||||||
| 
 | 
 | ||||||
| func TestVerify(t *testing.T) { | func TestVerify(t *testing.T) { | ||||||
| 	srvResource := &auth.Resource{ | 	srvResource := &Resource{ | ||||||
| 		Type:     "service", | 		Type:     "service", | ||||||
| 		Name:     "go.micro.service.foo", | 		Name:     "go.micro.service.foo", | ||||||
| 		Endpoint: "Foo.Bar", | 		Endpoint: "Foo.Bar", | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	webResource := &auth.Resource{ | 	webResource := &Resource{ | ||||||
| 		Type:     "service", | 		Type:     "service", | ||||||
| 		Name:     "go.micro.web.foo", | 		Name:     "go.micro.web.foo", | ||||||
| 		Endpoint: "/foo/bar", | 		Endpoint: "/foo/bar", | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	catchallResource := &auth.Resource{ | 	catchallResource := &Resource{ | ||||||
| 		Type:     "*", | 		Type:     "*", | ||||||
| 		Name:     "*", | 		Name:     "*", | ||||||
| 		Endpoint: "*", | 		Endpoint: "*", | ||||||
| @@ -27,24 +25,24 @@ func TestVerify(t *testing.T) { | |||||||
| 
 | 
 | ||||||
| 	tt := []struct { | 	tt := []struct { | ||||||
| 		Name     string | 		Name     string | ||||||
| 		Rules    []*auth.Rule | 		Rules    []*Rule | ||||||
| 		Account  *auth.Account | 		Account  *Account | ||||||
| 		Resource *auth.Resource | 		Resource *Resource | ||||||
| 		Error    error | 		Error    error | ||||||
| 	}{ | 	}{ | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "NoRules", | 			Name:     "NoRules", | ||||||
| 			Rules:    []*auth.Rule{}, | 			Rules:    []*Rule{}, | ||||||
| 			Account:  nil, | 			Account:  nil, | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Error:    auth.ErrForbidden, | 			Error:    ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallPublicAccount", | 			Name:     "CatchallPublicAccount", | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "", | 					Scope:    "", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 				}, | 				}, | ||||||
| @@ -53,8 +51,8 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallPublicNoAccount", | 			Name:     "CatchallPublicNoAccount", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "", | 					Scope:    "", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 				}, | 				}, | ||||||
| @@ -62,10 +60,10 @@ func TestVerify(t *testing.T) { | |||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallPrivateAccount", | 			Name:     "CatchallPrivateAccount", | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 				}, | 				}, | ||||||
| @@ -74,22 +72,22 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallPrivateNoAccount", | 			Name:     "CatchallPrivateNoAccount", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallServiceRuleMatch", | 			Name:     "CatchallServiceRuleMatch", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     srvResource.Type, | 						Type:     srvResource.Type, | ||||||
| 						Name:     srvResource.Name, | 						Name:     srvResource.Name, | ||||||
| 						Endpoint: "*", | 						Endpoint: "*", | ||||||
| @@ -100,27 +98,27 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallServiceRuleNoMatch", | 			Name:     "CatchallServiceRuleNoMatch", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     srvResource.Type, | 						Type:     srvResource.Type, | ||||||
| 						Name:     "wrongname", | 						Name:     "wrongname", | ||||||
| 						Endpoint: "*", | 						Endpoint: "*", | ||||||
| 					}, | 					}, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "ExactRuleValidScope", | 			Name:     "ExactRuleValidScope", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account: &auth.Account{ | 			Account: &Account{ | ||||||
| 				Scopes: []string{"neededscope"}, | 				Scopes: []string{"neededscope"}, | ||||||
| 			}, | 			}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "neededscope", | 					Scope:    "neededscope", | ||||||
| 					Resource: srvResource, | 					Resource: srvResource, | ||||||
| 				}, | 				}, | ||||||
| @@ -129,58 +127,58 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "ExactRuleInvalidScope", | 			Name:     "ExactRuleInvalidScope", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account: &auth.Account{ | 			Account: &Account{ | ||||||
| 				Scopes: []string{"neededscope"}, | 				Scopes: []string{"neededscope"}, | ||||||
| 			}, | 			}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "invalidscope", | 					Scope:    "invalidscope", | ||||||
| 					Resource: srvResource, | 					Resource: srvResource, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallDenyWithAccount", | 			Name:     "CatchallDenyWithAccount", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessDenied, | 					Access:   AccessDenied, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "CatchallDenyWithNoAccount", | 			Name:     "CatchallDenyWithNoAccount", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessDenied, | 					Access:   AccessDenied, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "RulePriorityGrantFirst", | 			Name:     "RulePriorityGrantFirst", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessGranted, | 					Access:   AccessGranted, | ||||||
| 					Priority: 1, | 					Priority: 1, | ||||||
| 				}, | 				}, | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessDenied, | 					Access:   AccessDenied, | ||||||
| 					Priority: 0, | 					Priority: 0, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| @@ -188,29 +186,29 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "RulePriorityDenyFirst", | 			Name:     "RulePriorityDenyFirst", | ||||||
| 			Resource: srvResource, | 			Resource: srvResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessGranted, | 					Access:   AccessGranted, | ||||||
| 					Priority: 0, | 					Priority: 0, | ||||||
| 				}, | 				}, | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: catchallResource, | 					Resource: catchallResource, | ||||||
| 					Access:   auth.AccessDenied, | 					Access:   AccessDenied, | ||||||
| 					Priority: 1, | 					Priority: 1, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "WebExactEndpointValid", | 			Name:     "WebExactEndpointValid", | ||||||
| 			Resource: webResource, | 			Resource: webResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope:    "*", | 					Scope:    "*", | ||||||
| 					Resource: webResource, | 					Resource: webResource, | ||||||
| 				}, | 				}, | ||||||
| @@ -219,27 +217,27 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "WebExactEndpointInalid", | 			Name:     "WebExactEndpointInalid", | ||||||
| 			Resource: webResource, | 			Resource: webResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     webResource.Type, | 						Type:     webResource.Type, | ||||||
| 						Name:     webResource.Name, | 						Name:     webResource.Name, | ||||||
| 						Endpoint: "invalidendpoint", | 						Endpoint: "invalidendpoint", | ||||||
| 					}, | 					}, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 		{ | 		{ | ||||||
| 			Name:     "WebWildcardEndpoint", | 			Name:     "WebWildcardEndpoint", | ||||||
| 			Resource: webResource, | 			Resource: webResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     webResource.Type, | 						Type:     webResource.Type, | ||||||
| 						Name:     webResource.Name, | 						Name:     webResource.Name, | ||||||
| 						Endpoint: "*", | 						Endpoint: "*", | ||||||
| @@ -250,11 +248,11 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "WebWildcardPathEndpointValid", | 			Name:     "WebWildcardPathEndpointValid", | ||||||
| 			Resource: webResource, | 			Resource: webResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     webResource.Type, | 						Type:     webResource.Type, | ||||||
| 						Name:     webResource.Name, | 						Name:     webResource.Name, | ||||||
| 						Endpoint: "/foo/*", | 						Endpoint: "/foo/*", | ||||||
| @@ -265,24 +263,24 @@ func TestVerify(t *testing.T) { | |||||||
| 		{ | 		{ | ||||||
| 			Name:     "WebWildcardPathEndpointInvalid", | 			Name:     "WebWildcardPathEndpointInvalid", | ||||||
| 			Resource: webResource, | 			Resource: webResource, | ||||||
| 			Account:  &auth.Account{}, | 			Account:  &Account{}, | ||||||
| 			Rules: []*auth.Rule{ | 			Rules: []*Rule{ | ||||||
| 				&auth.Rule{ | 				{ | ||||||
| 					Scope: "*", | 					Scope: "*", | ||||||
| 					Resource: &auth.Resource{ | 					Resource: &Resource{ | ||||||
| 						Type:     webResource.Type, | 						Type:     webResource.Type, | ||||||
| 						Name:     webResource.Name, | 						Name:     webResource.Name, | ||||||
| 						Endpoint: "/bar/*", | 						Endpoint: "/bar/*", | ||||||
| 					}, | 					}, | ||||||
| 				}, | 				}, | ||||||
| 			}, | 			}, | ||||||
| 			Error: auth.ErrForbidden, | 			Error: ErrForbidden, | ||||||
| 		}, | 		}, | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	for _, tc := range tt { | 	for _, tc := range tt { | ||||||
| 		t.Run(tc.Name, func(t *testing.T) { | 		t.Run(tc.Name, func(t *testing.T) { | ||||||
| 			if err := Verify(tc.Rules, tc.Account, tc.Resource); err != tc.Error { | 			if err := VerifyAccess(tc.Rules, tc.Account, tc.Resource); err != tc.Error { | ||||||
| 				t.Errorf("Expected %v but got %v", tc.Error, err) | 				t.Errorf("Expected %v but got %v", tc.Error, err) | ||||||
| 			} | 			} | ||||||
| 		}) | 		}) | ||||||
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							| @@ -1,279 +0,0 @@ | |||||||
| // Code generated by protoc-gen-micro. DO NOT EDIT. |  | ||||||
| // source: auth/service/proto/auth.proto |  | ||||||
|  |  | ||||||
| package go_micro_auth |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	fmt "fmt" |  | ||||||
| 	proto "github.com/golang/protobuf/proto" |  | ||||||
| 	math "math" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	context "context" |  | ||||||
| 	api "github.com/micro/go-micro/v2/api" |  | ||||||
| 	client "github.com/micro/go-micro/v2/client" |  | ||||||
| 	server "github.com/micro/go-micro/v2/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 Auth service |  | ||||||
|  |  | ||||||
| func NewAuthEndpoints() []*api.Endpoint { |  | ||||||
| 	return []*api.Endpoint{} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Client API for Auth service |  | ||||||
|  |  | ||||||
| type AuthService interface { |  | ||||||
| 	Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error) |  | ||||||
| 	Inspect(ctx context.Context, in *InspectRequest, opts ...client.CallOption) (*InspectResponse, error) |  | ||||||
| 	Token(ctx context.Context, in *TokenRequest, opts ...client.CallOption) (*TokenResponse, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type authService struct { |  | ||||||
| 	c    client.Client |  | ||||||
| 	name string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewAuthService(name string, c client.Client) AuthService { |  | ||||||
| 	return &authService{ |  | ||||||
| 		c:    c, |  | ||||||
| 		name: name, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *authService) Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Auth.Generate", in) |  | ||||||
| 	out := new(GenerateResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *authService) Inspect(ctx context.Context, in *InspectRequest, opts ...client.CallOption) (*InspectResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Auth.Inspect", in) |  | ||||||
| 	out := new(InspectResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *authService) Token(ctx context.Context, in *TokenRequest, opts ...client.CallOption) (*TokenResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Auth.Token", in) |  | ||||||
| 	out := new(TokenResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Server API for Auth service |  | ||||||
|  |  | ||||||
| type AuthHandler interface { |  | ||||||
| 	Generate(context.Context, *GenerateRequest, *GenerateResponse) error |  | ||||||
| 	Inspect(context.Context, *InspectRequest, *InspectResponse) error |  | ||||||
| 	Token(context.Context, *TokenRequest, *TokenResponse) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func RegisterAuthHandler(s server.Server, hdlr AuthHandler, opts ...server.HandlerOption) error { |  | ||||||
| 	type auth interface { |  | ||||||
| 		Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error |  | ||||||
| 		Inspect(ctx context.Context, in *InspectRequest, out *InspectResponse) error |  | ||||||
| 		Token(ctx context.Context, in *TokenRequest, out *TokenResponse) error |  | ||||||
| 	} |  | ||||||
| 	type Auth struct { |  | ||||||
| 		auth |  | ||||||
| 	} |  | ||||||
| 	h := &authHandler{hdlr} |  | ||||||
| 	return s.Handle(s.NewHandler(&Auth{h}, opts...)) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type authHandler struct { |  | ||||||
| 	AuthHandler |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *authHandler) Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error { |  | ||||||
| 	return h.AuthHandler.Generate(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *authHandler) Inspect(ctx context.Context, in *InspectRequest, out *InspectResponse) error { |  | ||||||
| 	return h.AuthHandler.Inspect(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *authHandler) Token(ctx context.Context, in *TokenRequest, out *TokenResponse) error { |  | ||||||
| 	return h.AuthHandler.Token(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Api Endpoints for Accounts service |  | ||||||
|  |  | ||||||
| func NewAccountsEndpoints() []*api.Endpoint { |  | ||||||
| 	return []*api.Endpoint{} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Client API for Accounts service |  | ||||||
|  |  | ||||||
| type AccountsService interface { |  | ||||||
| 	List(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type accountsService struct { |  | ||||||
| 	c    client.Client |  | ||||||
| 	name string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewAccountsService(name string, c client.Client) AccountsService { |  | ||||||
| 	return &accountsService{ |  | ||||||
| 		c:    c, |  | ||||||
| 		name: name, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *accountsService) List(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Accounts.List", in) |  | ||||||
| 	out := new(ListAccountsResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Server API for Accounts service |  | ||||||
|  |  | ||||||
| type AccountsHandler interface { |  | ||||||
| 	List(context.Context, *ListAccountsRequest, *ListAccountsResponse) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func RegisterAccountsHandler(s server.Server, hdlr AccountsHandler, opts ...server.HandlerOption) error { |  | ||||||
| 	type accounts interface { |  | ||||||
| 		List(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error |  | ||||||
| 	} |  | ||||||
| 	type Accounts struct { |  | ||||||
| 		accounts |  | ||||||
| 	} |  | ||||||
| 	h := &accountsHandler{hdlr} |  | ||||||
| 	return s.Handle(s.NewHandler(&Accounts{h}, opts...)) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type accountsHandler struct { |  | ||||||
| 	AccountsHandler |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *accountsHandler) List(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error { |  | ||||||
| 	return h.AccountsHandler.List(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Api Endpoints for Rules service |  | ||||||
|  |  | ||||||
| func NewRulesEndpoints() []*api.Endpoint { |  | ||||||
| 	return []*api.Endpoint{} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Client API for Rules service |  | ||||||
|  |  | ||||||
| type RulesService interface { |  | ||||||
| 	Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) |  | ||||||
| 	Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) |  | ||||||
| 	List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type rulesService struct { |  | ||||||
| 	c    client.Client |  | ||||||
| 	name string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewRulesService(name string, c client.Client) RulesService { |  | ||||||
| 	return &rulesService{ |  | ||||||
| 		c:    c, |  | ||||||
| 		name: name, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *rulesService) Create(ctx context.Context, in *CreateRequest, opts ...client.CallOption) (*CreateResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Rules.Create", in) |  | ||||||
| 	out := new(CreateResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *rulesService) Delete(ctx context.Context, in *DeleteRequest, opts ...client.CallOption) (*DeleteResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Rules.Delete", in) |  | ||||||
| 	out := new(DeleteResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *rulesService) List(ctx context.Context, in *ListRequest, opts ...client.CallOption) (*ListResponse, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Rules.List", in) |  | ||||||
| 	out := new(ListResponse) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Server API for Rules service |  | ||||||
|  |  | ||||||
| type RulesHandler interface { |  | ||||||
| 	Create(context.Context, *CreateRequest, *CreateResponse) error |  | ||||||
| 	Delete(context.Context, *DeleteRequest, *DeleteResponse) error |  | ||||||
| 	List(context.Context, *ListRequest, *ListResponse) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func RegisterRulesHandler(s server.Server, hdlr RulesHandler, opts ...server.HandlerOption) error { |  | ||||||
| 	type rules interface { |  | ||||||
| 		Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error |  | ||||||
| 		Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error |  | ||||||
| 		List(ctx context.Context, in *ListRequest, out *ListResponse) error |  | ||||||
| 	} |  | ||||||
| 	type Rules struct { |  | ||||||
| 		rules |  | ||||||
| 	} |  | ||||||
| 	h := &rulesHandler{hdlr} |  | ||||||
| 	return s.Handle(s.NewHandler(&Rules{h}, opts...)) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type rulesHandler struct { |  | ||||||
| 	RulesHandler |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *rulesHandler) Create(ctx context.Context, in *CreateRequest, out *CreateResponse) error { |  | ||||||
| 	return h.RulesHandler.Create(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *rulesHandler) Delete(ctx context.Context, in *DeleteRequest, out *DeleteResponse) error { |  | ||||||
| 	return h.RulesHandler.Delete(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *rulesHandler) List(ctx context.Context, in *ListRequest, out *ListResponse) error { |  | ||||||
| 	return h.RulesHandler.List(ctx, in, out) |  | ||||||
| } |  | ||||||
| @@ -1,127 +0,0 @@ | |||||||
| syntax = "proto3"; |  | ||||||
|  |  | ||||||
| package go.micro.auth; |  | ||||||
|  |  | ||||||
| service Auth { |  | ||||||
| 	rpc Generate(GenerateRequest) returns (GenerateResponse) {}; |  | ||||||
| 	rpc Inspect(InspectRequest) returns (InspectResponse) {};		 |  | ||||||
| 	rpc Token(TokenRequest) returns (TokenResponse) {}; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| service Accounts { |  | ||||||
| 	rpc List(ListAccountsRequest) returns (ListAccountsResponse) {}; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| service Rules { |  | ||||||
| 	rpc Create(CreateRequest) returns (CreateResponse) {}; |  | ||||||
| 	rpc Delete(DeleteRequest) returns (DeleteResponse) {}; |  | ||||||
| 	rpc List(ListRequest) returns (ListResponse) {}; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message ListAccountsRequest { |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message ListAccountsResponse { |  | ||||||
| 	repeated Account accounts = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Token { |  | ||||||
| 	string access_token = 1; |  | ||||||
| 	string refresh_token = 2; |  | ||||||
| 	int64 created = 3; |  | ||||||
| 	int64 expiry = 4; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Account { |  | ||||||
| 	string id = 1; |  | ||||||
| 	string type = 2; |  | ||||||
| 	map<string, string> metadata = 4; |  | ||||||
| 	repeated string scopes = 5; |  | ||||||
| 	string issuer = 6; |  | ||||||
| 	string secret = 7; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Resource{ |  | ||||||
| 	string name = 1; |  | ||||||
| 	string type = 2; |  | ||||||
| 	string endpoint = 3; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message GenerateRequest { |  | ||||||
| 	string id = 1; |  | ||||||
| 	map<string, string> metadata = 3; |  | ||||||
| 	repeated string scopes = 4; |  | ||||||
| 	string secret = 5; |  | ||||||
| 	string type = 6; |  | ||||||
| 	string provider = 7; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message GenerateResponse { |  | ||||||
| 	Account account = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message GrantRequest { |  | ||||||
| 	string scope = 1; |  | ||||||
| 	Resource resource = 2; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message GrantResponse {} |  | ||||||
|  |  | ||||||
| message RevokeRequest { |  | ||||||
| 	string scope = 1; |  | ||||||
| 	Resource resource = 2; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message RevokeResponse {} |  | ||||||
|  |  | ||||||
| message InspectRequest { |  | ||||||
| 	string token = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message InspectResponse { |  | ||||||
| 	Account account = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message TokenRequest { |  | ||||||
| 	string id = 1; |  | ||||||
| 	string secret = 2; |  | ||||||
| 	string refresh_token = 3; |  | ||||||
| 	int64 token_expiry = 4; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message TokenResponse { |  | ||||||
| 	Token token = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| enum Access { |  | ||||||
| 	UNKNOWN = 0; |  | ||||||
| 	GRANTED = 1; |  | ||||||
| 	DENIED = 2; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Rule { |  | ||||||
| 	string id = 1; |  | ||||||
| 	string scope = 2; |  | ||||||
| 	Resource resource = 3; |  | ||||||
| 	Access access = 4; |  | ||||||
| 	int32 priority = 5; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message CreateRequest { |  | ||||||
| 	Rule rule = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message CreateResponse {} |  | ||||||
|  |  | ||||||
| message DeleteRequest { |  | ||||||
| 	string id = 1; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message DeleteResponse {} |  | ||||||
|  |  | ||||||
| message ListRequest { |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message ListResponse { |  | ||||||
| 	repeated Rule rules = 1; |  | ||||||
| } |  | ||||||
| @@ -1,228 +0,0 @@ | |||||||
| package service |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"strings" |  | ||||||
| 	"time" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/auth" |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/rules" |  | ||||||
| 	pb "github.com/micro/go-micro/v2/auth/service/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/token" |  | ||||||
| 	"github.com/micro/go-micro/v2/auth/token/jwt" |  | ||||||
| 	"github.com/micro/go-micro/v2/client" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // svc is the service implementation of the Auth interface |  | ||||||
| type svc struct { |  | ||||||
| 	options auth.Options |  | ||||||
| 	auth    pb.AuthService |  | ||||||
| 	rules   pb.RulesService |  | ||||||
| 	jwt     token.Provider |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *svc) String() string { |  | ||||||
| 	return "service" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *svc) Init(opts ...auth.Option) { |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&s.options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	if s.options.Client == nil { |  | ||||||
| 		s.options.Client = client.DefaultClient |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	s.auth = pb.NewAuthService("go.micro.auth", s.options.Client) |  | ||||||
| 	s.rules = pb.NewRulesService("go.micro.auth", s.options.Client) |  | ||||||
|  |  | ||||||
| 	// if we have a JWT public key passed as an option, |  | ||||||
| 	// we can decode tokens with the type "JWT" locally |  | ||||||
| 	// and not have to make an RPC call |  | ||||||
| 	if key := s.options.PublicKey; len(key) > 0 { |  | ||||||
| 		s.jwt = jwt.NewTokenProvider(token.WithPublicKey(key)) |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *svc) Options() auth.Options { |  | ||||||
| 	return s.options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Generate a new account |  | ||||||
| func (s *svc) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { |  | ||||||
| 	options := auth.NewGenerateOptions(opts...) |  | ||||||
|  |  | ||||||
| 	rsp, err := s.auth.Generate(context.TODO(), &pb.GenerateRequest{ |  | ||||||
| 		Id:       id, |  | ||||||
| 		Type:     options.Type, |  | ||||||
| 		Secret:   options.Secret, |  | ||||||
| 		Scopes:   options.Scopes, |  | ||||||
| 		Metadata: options.Metadata, |  | ||||||
| 		Provider: options.Provider, |  | ||||||
| 	}) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return serializeAccount(rsp.Account), nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Grant access to a resource |  | ||||||
| func (s *svc) Grant(rule *auth.Rule) error { |  | ||||||
| 	access := pb.Access_UNKNOWN |  | ||||||
| 	if rule.Access == auth.AccessGranted { |  | ||||||
| 		access = pb.Access_GRANTED |  | ||||||
| 	} else if rule.Access == auth.AccessDenied { |  | ||||||
| 		access = pb.Access_DENIED |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	_, err := s.rules.Create(context.TODO(), &pb.CreateRequest{ |  | ||||||
| 		Rule: &pb.Rule{ |  | ||||||
| 			Id:       rule.ID, |  | ||||||
| 			Scope:    rule.Scope, |  | ||||||
| 			Priority: rule.Priority, |  | ||||||
| 			Access:   access, |  | ||||||
| 			Resource: &pb.Resource{ |  | ||||||
| 				Type:     rule.Resource.Type, |  | ||||||
| 				Name:     rule.Resource.Name, |  | ||||||
| 				Endpoint: rule.Resource.Endpoint, |  | ||||||
| 			}, |  | ||||||
| 		}, |  | ||||||
| 	}) |  | ||||||
|  |  | ||||||
| 	return err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Revoke access to a resource |  | ||||||
| func (s *svc) Revoke(rule *auth.Rule) error { |  | ||||||
| 	_, err := s.rules.Delete(context.TODO(), &pb.DeleteRequest{ |  | ||||||
| 		Id: rule.ID, |  | ||||||
| 	}) |  | ||||||
|  |  | ||||||
| 	return err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *svc) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) { |  | ||||||
| 	var options auth.RulesOptions |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	if options.Context == nil { |  | ||||||
| 		options.Context = context.TODO() |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	rsp, err := s.rules.List(options.Context, &pb.ListRequest{}, client.WithCache(time.Second*30)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	rules := make([]*auth.Rule, len(rsp.Rules)) |  | ||||||
| 	for i, r := range rsp.Rules { |  | ||||||
| 		rules[i] = serializeRule(r) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return rules, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Verify an account has access to a resource |  | ||||||
| func (s *svc) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error { |  | ||||||
| 	var options auth.VerifyOptions |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	rs, err := s.Rules(auth.RulesContext(options.Context)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return rules.Verify(rs, acc, res) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Inspect a token |  | ||||||
| func (s *svc) Inspect(token string) (*auth.Account, error) { |  | ||||||
| 	// try to decode JWT locally and fall back to srv if an error occurs |  | ||||||
| 	if len(strings.Split(token, ".")) == 3 && s.jwt != nil { |  | ||||||
| 		return s.jwt.Inspect(token) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	// the token is not a JWT or we do not have the keys to decode it, |  | ||||||
| 	// fall back to the auth service |  | ||||||
| 	rsp, err := s.auth.Inspect(context.TODO(), &pb.InspectRequest{Token: token}) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return serializeAccount(rsp.Account), nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Token generation using an account ID and secret |  | ||||||
| func (s *svc) Token(opts ...auth.TokenOption) (*auth.Token, error) { |  | ||||||
| 	options := auth.NewTokenOptions(opts...) |  | ||||||
|  |  | ||||||
| 	rsp, err := s.auth.Token(context.Background(), &pb.TokenRequest{ |  | ||||||
| 		Id:           options.ID, |  | ||||||
| 		Secret:       options.Secret, |  | ||||||
| 		RefreshToken: options.RefreshToken, |  | ||||||
| 		TokenExpiry:  int64(options.Expiry.Seconds()), |  | ||||||
| 	}) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return serializeToken(rsp.Token), nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func serializeToken(t *pb.Token) *auth.Token { |  | ||||||
| 	return &auth.Token{ |  | ||||||
| 		AccessToken:  t.AccessToken, |  | ||||||
| 		RefreshToken: t.RefreshToken, |  | ||||||
| 		Created:      time.Unix(t.Created, 0), |  | ||||||
| 		Expiry:       time.Unix(t.Expiry, 0), |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func serializeAccount(a *pb.Account) *auth.Account { |  | ||||||
| 	return &auth.Account{ |  | ||||||
| 		ID:       a.Id, |  | ||||||
| 		Secret:   a.Secret, |  | ||||||
| 		Issuer:   a.Issuer, |  | ||||||
| 		Metadata: a.Metadata, |  | ||||||
| 		Scopes:   a.Scopes, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func serializeRule(r *pb.Rule) *auth.Rule { |  | ||||||
| 	var access auth.Access |  | ||||||
| 	if r.Access == pb.Access_GRANTED { |  | ||||||
| 		access = auth.AccessGranted |  | ||||||
| 	} else { |  | ||||||
| 		access = auth.AccessDenied |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return &auth.Rule{ |  | ||||||
| 		ID:       r.Id, |  | ||||||
| 		Scope:    r.Scope, |  | ||||||
| 		Access:   access, |  | ||||||
| 		Priority: r.Priority, |  | ||||||
| 		Resource: &auth.Resource{ |  | ||||||
| 			Type:     r.Resource.Type, |  | ||||||
| 			Name:     r.Resource.Name, |  | ||||||
| 			Endpoint: r.Resource.Endpoint, |  | ||||||
| 		}, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // NewAuth returns a new instance of the Auth service |  | ||||||
| func NewAuth(opts ...auth.Option) auth.Auth { |  | ||||||
| 	options := auth.NewOptions(opts...) |  | ||||||
| 	if options.Client == nil { |  | ||||||
| 		options.Client = client.DefaultClient |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	return &svc{ |  | ||||||
| 		auth:    pb.NewAuthService("go.micro.auth", options.Client), |  | ||||||
| 		rules:   pb.NewRulesService("go.micro.auth", options.Client), |  | ||||||
| 		options: options, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
| @@ -1,6 +1,10 @@ | |||||||
| // Package broker is an interface used for asynchronous messaging | // Package broker is an interface used for asynchronous messaging | ||||||
| package broker | package broker | ||||||
|  |  | ||||||
|  | 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 | ||||||
| @@ -14,15 +18,8 @@ type Broker interface { | |||||||
| } | } | ||||||
|  |  | ||||||
| // 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,37 +28,16 @@ type Event interface { | |||||||
| 	Error() error | 	Error() error | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // Message is used to transfer data | ||||||
|  | type Message struct { | ||||||
|  | 	Header map[string]string | ||||||
|  | 	Body   []byte | ||||||
|  | 	Error  error | ||||||
|  | } | ||||||
|  |  | ||||||
| // 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() error | ||||||
| } | } | ||||||
|  |  | ||||||
| var ( |  | ||||||
| 	DefaultBroker Broker = NewBroker() |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func Init(opts ...Option) error { |  | ||||||
| 	return DefaultBroker.Init(opts...) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func Connect() error { |  | ||||||
| 	return DefaultBroker.Connect() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func Disconnect() error { |  | ||||||
| 	return DefaultBroker.Disconnect() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func Publish(topic string, msg *Message, opts ...PublishOption) error { |  | ||||||
| 	return DefaultBroker.Publish(topic, msg, opts...) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) { |  | ||||||
| 	return DefaultBroker.Subscribe(topic, handler, opts...) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func String() string { |  | ||||||
| 	return DefaultBroker.String() |  | ||||||
| } |  | ||||||
|   | |||||||
							
								
								
									
										711
									
								
								broker/http.go
									
									
									
									
									
								
							
							
						
						
									
										711
									
								
								broker/http.go
									
									
									
									
									
								
							| @@ -1,711 +0,0 @@ | |||||||
| // Package http provides a http based message broker |  | ||||||
| package broker |  | ||||||
|  |  | ||||||
| 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/v2/codec/json" |  | ||||||
| 	merr "github.com/micro/go-micro/v2/errors" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry/cache" |  | ||||||
| 	maddr "github.com/micro/go-micro/v2/util/addr" |  | ||||||
| 	mnet "github.com/micro/go-micro/v2/util/net" |  | ||||||
| 	mls "github.com/micro/go-micro/v2/util/tls" |  | ||||||
| 	"golang.org/x/net/http2" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // HTTP Broker is a point to point async broker |  | ||||||
| type httpBroker struct { |  | ||||||
| 	id      string |  | ||||||
| 	address string |  | ||||||
| 	opts    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  SubscribeOptions |  | ||||||
| 	id    string |  | ||||||
| 	topic string |  | ||||||
| 	fn    Handler |  | ||||||
| 	svc   *registry.Service |  | ||||||
| 	hb    *httpBroker |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type httpEvent struct { |  | ||||||
| 	m   *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 ...Option) Broker { |  | ||||||
| 	options := Options{ |  | ||||||
| 		Codec:    json.Marshaler{}, |  | ||||||
| 		Context:  context.TODO(), |  | ||||||
| 		Registry: registry.DefaultRegistry, |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	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() *Message { |  | ||||||
| 	return h.m |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *httpEvent) Topic() string { |  | ||||||
| 	return h.t |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *httpSubscriber) Options() 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 *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 []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 = registry.DefaultRegistry |  | ||||||
| 	} |  | ||||||
| 	// 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 ...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 = registry.DefaultRegistry |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	// 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() Options { |  | ||||||
| 	return h.opts |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption) error { |  | ||||||
| 	// create the message first |  | ||||||
| 	m := &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 Handler, opts ...SubscribeOption) (Subscriber, error) { |  | ||||||
| 	var err error |  | ||||||
| 	var host, port string |  | ||||||
| 	options := 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 ...Option) Broker { |  | ||||||
| 	return newHttpBroker(opts...) |  | ||||||
| } |  | ||||||
| @@ -1,11 +0,0 @@ | |||||||
| // Package http provides a http based message broker |  | ||||||
| package http |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"github.com/micro/go-micro/v2/broker" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| // NewBroker returns a new http broker |  | ||||||
| func NewBroker(opts ...broker.Option) broker.Broker { |  | ||||||
| 	return broker.NewBroker(opts...) |  | ||||||
| } |  | ||||||
| @@ -1,23 +0,0 @@ | |||||||
| package http |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"net/http" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/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,384 +0,0 @@ | |||||||
| package broker_test |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"sync" |  | ||||||
| 	"testing" |  | ||||||
| 	"time" |  | ||||||
|  |  | ||||||
| 	"github.com/google/uuid" |  | ||||||
| 	"github.com/micro/go-micro/v2/broker" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry" |  | ||||||
| 	"github.com/micro/go-micro/v2/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 := broker.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 := broker.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 := broker.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 := broker.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 := broker.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,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/v2/broker" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| 	maddr "github.com/micro/go-micro/v2/util/addr" |  | ||||||
| 	mnet "github.com/micro/go-micro/v2/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/v2/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/v2/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,318 +0,0 @@ | |||||||
| // Package nats provides a NATS broker |  | ||||||
| package nats |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"errors" |  | ||||||
| 	"strings" |  | ||||||
| 	"sync" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/broker" |  | ||||||
| 	"github.com/micro/go-micro/v2/codec/json" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| 	"github.com/micro/go-micro/v2/registry" |  | ||||||
| 	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 { |  | ||||||
| 			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: registry.DefaultRegistry, |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	n := &natsBroker{ |  | ||||||
| 		opts: options, |  | ||||||
| 	} |  | ||||||
| 	n.setOption(opts...) |  | ||||||
|  |  | ||||||
| 	return n |  | ||||||
| } |  | ||||||
| @@ -1,98 +0,0 @@ | |||||||
| package nats |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"fmt" |  | ||||||
| 	"testing" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/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/v2/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{}{}) |  | ||||||
| } |  | ||||||
							
								
								
									
										74
									
								
								broker/noop.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										74
									
								
								broker/noop.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,74 @@ | |||||||
|  | package broker | ||||||
|  |  | ||||||
|  | type noopBroker struct { | ||||||
|  | 	opts Options | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type noopSubscriber struct { | ||||||
|  | 	topic string | ||||||
|  | 	opts  SubscribeOptions | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Init(opts ...Option) error { | ||||||
|  | 	for _, o := range opts { | ||||||
|  | 		o(&n.opts) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Options() Options { | ||||||
|  | 	return n.opts | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Address() string { | ||||||
|  | 	return "" | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Connect() error { | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Disconnect() error { | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Publish(topic string, m *Message, opts ...PublishOption) error { | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) { | ||||||
|  | 	options := NewSubscribeOptions() | ||||||
|  |  | ||||||
|  | 	for _, o := range opts { | ||||||
|  | 		o(&options) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return &noopSubscriber{topic: topic, opts: options}, nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopBroker) String() string { | ||||||
|  | 	return "noop" | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopSubscriber) Options() SubscribeOptions { | ||||||
|  | 	return n.opts | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopSubscriber) Topic() string { | ||||||
|  | 	return n.topic | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (n *noopSubscriber) Unsubscribe() error { | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // newBroker returns a new noop broker | ||||||
|  | func newBroker(opts ...Option) Broker { | ||||||
|  | 	options := NewOptions() | ||||||
|  |  | ||||||
|  | 	for _, o := range opts { | ||||||
|  | 		o(&options) | ||||||
|  | 	} | ||||||
|  | 	return &noopBroker{opts: options} | ||||||
|  | } | ||||||
| @@ -4,8 +4,9 @@ import ( | |||||||
| 	"context" | 	"context" | ||||||
| 	"crypto/tls" | 	"crypto/tls" | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/codec" | 	"github.com/unistack-org/micro/v3/codec" | ||||||
| 	"github.com/micro/go-micro/v2/registry" | 	"github.com/unistack-org/micro/v3/logger" | ||||||
|  | 	"github.com/unistack-org/micro/v3/registry" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type Options struct { | type Options struct { | ||||||
| @@ -13,8 +14,9 @@ type Options struct { | |||||||
| 	Secure bool | 	Secure bool | ||||||
| 	Codec  codec.Marshaler | 	Codec  codec.Marshaler | ||||||
|  |  | ||||||
| 	// Handler executed when error happens in broker mesage | 	// Logger | ||||||
| 	// processing | 	Logger logger.Logger | ||||||
|  | 	// Handler executed when errors occur processing messages | ||||||
| 	ErrorHandler Handler | 	ErrorHandler Handler | ||||||
|  |  | ||||||
| 	TLSConfig *tls.Config | 	TLSConfig *tls.Config | ||||||
| @@ -25,6 +27,12 @@ type Options struct { | |||||||
| 	Context context.Context | 	Context context.Context | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func NewOptions() Options { | ||||||
|  | 	return Options{ | ||||||
|  | 		Context: context.Background(), | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| 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 | ||||||
| @@ -32,13 +40,16 @@ type PublishOptions 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 | ||||||
| @@ -61,6 +72,7 @@ type SubscribeOption func(*SubscribeOptions) | |||||||
| func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions { | func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions { | ||||||
| 	opt := SubscribeOptions{ | 	opt := SubscribeOptions{ | ||||||
| 		AutoAck: true, | 		AutoAck: true, | ||||||
|  | 		Context: context.Background(), | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
| @@ -85,14 +97,20 @@ func Codec(c codec.Marshaler) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| // DisableAutoAck will disable auto acking of messages |  | ||||||
| // 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,10 +119,24 @@ 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 | ||||||
|  | // in normal way, for example Codec errors | ||||||
|  | func SubscribeErrorHandler(h Handler) SubscribeOption { | ||||||
|  | 	return func(o *SubscribeOptions) { | ||||||
|  | 		o.ErrorHandler = h | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| func Queue(name string) SubscribeOption { | func Queue(name string) SubscribeOption { | ||||||
| 	return func(o *SubscribeOptions) { | 	return func(o *SubscribeOptions) { | ||||||
| 		o.Queue = name | 		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 | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -128,6 +160,13 @@ func TLSConfig(t *tls.Config) Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // 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) { | ||||||
|   | |||||||
| @@ -1,374 +0,0 @@ | |||||||
| // Code generated by protoc-gen-go. DO NOT EDIT. |  | ||||||
| // source: broker/service/proto/broker.proto |  | ||||||
|  |  | ||||||
| package go_micro_broker |  | ||||||
|  |  | ||||||
| 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 Empty struct { |  | ||||||
| 	XXX_NoUnkeyedLiteral struct{} `json:"-"` |  | ||||||
| 	XXX_unrecognized     []byte   `json:"-"` |  | ||||||
| 	XXX_sizecache        int32    `json:"-"` |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *Empty) Reset()         { *m = Empty{} } |  | ||||||
| func (m *Empty) String() string { return proto.CompactTextString(m) } |  | ||||||
| func (*Empty) ProtoMessage()    {} |  | ||||||
| func (*Empty) Descriptor() ([]byte, []int) { |  | ||||||
| 	return fileDescriptor_df4d8f04292cf3fe, []int{0} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *Empty) XXX_Unmarshal(b []byte) error { |  | ||||||
| 	return xxx_messageInfo_Empty.Unmarshal(m, b) |  | ||||||
| } |  | ||||||
| func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |  | ||||||
| 	return xxx_messageInfo_Empty.Marshal(b, m, deterministic) |  | ||||||
| } |  | ||||||
| func (m *Empty) XXX_Merge(src proto.Message) { |  | ||||||
| 	xxx_messageInfo_Empty.Merge(m, src) |  | ||||||
| } |  | ||||||
| func (m *Empty) XXX_Size() int { |  | ||||||
| 	return xxx_messageInfo_Empty.Size(m) |  | ||||||
| } |  | ||||||
| func (m *Empty) XXX_DiscardUnknown() { |  | ||||||
| 	xxx_messageInfo_Empty.DiscardUnknown(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var xxx_messageInfo_Empty proto.InternalMessageInfo |  | ||||||
|  |  | ||||||
| type PublishRequest struct { |  | ||||||
| 	Topic                string   `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` |  | ||||||
| 	Message              *Message `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` |  | ||||||
| 	XXX_NoUnkeyedLiteral struct{} `json:"-"` |  | ||||||
| 	XXX_unrecognized     []byte   `json:"-"` |  | ||||||
| 	XXX_sizecache        int32    `json:"-"` |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *PublishRequest) Reset()         { *m = PublishRequest{} } |  | ||||||
| func (m *PublishRequest) String() string { return proto.CompactTextString(m) } |  | ||||||
| func (*PublishRequest) ProtoMessage()    {} |  | ||||||
| func (*PublishRequest) Descriptor() ([]byte, []int) { |  | ||||||
| 	return fileDescriptor_df4d8f04292cf3fe, []int{1} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *PublishRequest) XXX_Unmarshal(b []byte) error { |  | ||||||
| 	return xxx_messageInfo_PublishRequest.Unmarshal(m, b) |  | ||||||
| } |  | ||||||
| func (m *PublishRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |  | ||||||
| 	return xxx_messageInfo_PublishRequest.Marshal(b, m, deterministic) |  | ||||||
| } |  | ||||||
| func (m *PublishRequest) XXX_Merge(src proto.Message) { |  | ||||||
| 	xxx_messageInfo_PublishRequest.Merge(m, src) |  | ||||||
| } |  | ||||||
| func (m *PublishRequest) XXX_Size() int { |  | ||||||
| 	return xxx_messageInfo_PublishRequest.Size(m) |  | ||||||
| } |  | ||||||
| func (m *PublishRequest) XXX_DiscardUnknown() { |  | ||||||
| 	xxx_messageInfo_PublishRequest.DiscardUnknown(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var xxx_messageInfo_PublishRequest proto.InternalMessageInfo |  | ||||||
|  |  | ||||||
| func (m *PublishRequest) GetTopic() string { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Topic |  | ||||||
| 	} |  | ||||||
| 	return "" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *PublishRequest) GetMessage() *Message { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Message |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type SubscribeRequest struct { |  | ||||||
| 	Topic                string   `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` |  | ||||||
| 	Queue                string   `protobuf:"bytes,2,opt,name=queue,proto3" json:"queue,omitempty"` |  | ||||||
| 	XXX_NoUnkeyedLiteral struct{} `json:"-"` |  | ||||||
| 	XXX_unrecognized     []byte   `json:"-"` |  | ||||||
| 	XXX_sizecache        int32    `json:"-"` |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *SubscribeRequest) Reset()         { *m = SubscribeRequest{} } |  | ||||||
| func (m *SubscribeRequest) String() string { return proto.CompactTextString(m) } |  | ||||||
| func (*SubscribeRequest) ProtoMessage()    {} |  | ||||||
| func (*SubscribeRequest) Descriptor() ([]byte, []int) { |  | ||||||
| 	return fileDescriptor_df4d8f04292cf3fe, []int{2} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *SubscribeRequest) XXX_Unmarshal(b []byte) error { |  | ||||||
| 	return xxx_messageInfo_SubscribeRequest.Unmarshal(m, b) |  | ||||||
| } |  | ||||||
| func (m *SubscribeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |  | ||||||
| 	return xxx_messageInfo_SubscribeRequest.Marshal(b, m, deterministic) |  | ||||||
| } |  | ||||||
| func (m *SubscribeRequest) XXX_Merge(src proto.Message) { |  | ||||||
| 	xxx_messageInfo_SubscribeRequest.Merge(m, src) |  | ||||||
| } |  | ||||||
| func (m *SubscribeRequest) XXX_Size() int { |  | ||||||
| 	return xxx_messageInfo_SubscribeRequest.Size(m) |  | ||||||
| } |  | ||||||
| func (m *SubscribeRequest) XXX_DiscardUnknown() { |  | ||||||
| 	xxx_messageInfo_SubscribeRequest.DiscardUnknown(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var xxx_messageInfo_SubscribeRequest proto.InternalMessageInfo |  | ||||||
|  |  | ||||||
| func (m *SubscribeRequest) GetTopic() string { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Topic |  | ||||||
| 	} |  | ||||||
| 	return "" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *SubscribeRequest) GetQueue() string { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Queue |  | ||||||
| 	} |  | ||||||
| 	return "" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Message struct { |  | ||||||
| 	Header               map[string]string `protobuf:"bytes,1,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` |  | ||||||
| 	Body                 []byte            `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` |  | ||||||
| 	XXX_NoUnkeyedLiteral struct{}          `json:"-"` |  | ||||||
| 	XXX_unrecognized     []byte            `json:"-"` |  | ||||||
| 	XXX_sizecache        int32             `json:"-"` |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *Message) Reset()         { *m = Message{} } |  | ||||||
| func (m *Message) String() string { return proto.CompactTextString(m) } |  | ||||||
| func (*Message) ProtoMessage()    {} |  | ||||||
| func (*Message) Descriptor() ([]byte, []int) { |  | ||||||
| 	return fileDescriptor_df4d8f04292cf3fe, []int{3} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *Message) XXX_Unmarshal(b []byte) error { |  | ||||||
| 	return xxx_messageInfo_Message.Unmarshal(m, b) |  | ||||||
| } |  | ||||||
| func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |  | ||||||
| 	return xxx_messageInfo_Message.Marshal(b, m, deterministic) |  | ||||||
| } |  | ||||||
| func (m *Message) XXX_Merge(src proto.Message) { |  | ||||||
| 	xxx_messageInfo_Message.Merge(m, src) |  | ||||||
| } |  | ||||||
| func (m *Message) XXX_Size() int { |  | ||||||
| 	return xxx_messageInfo_Message.Size(m) |  | ||||||
| } |  | ||||||
| func (m *Message) XXX_DiscardUnknown() { |  | ||||||
| 	xxx_messageInfo_Message.DiscardUnknown(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var xxx_messageInfo_Message proto.InternalMessageInfo |  | ||||||
|  |  | ||||||
| func (m *Message) GetHeader() map[string]string { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Header |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *Message) GetBody() []byte { |  | ||||||
| 	if m != nil { |  | ||||||
| 		return m.Body |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func init() { |  | ||||||
| 	proto.RegisterType((*Empty)(nil), "go.micro.broker.Empty") |  | ||||||
| 	proto.RegisterType((*PublishRequest)(nil), "go.micro.broker.PublishRequest") |  | ||||||
| 	proto.RegisterType((*SubscribeRequest)(nil), "go.micro.broker.SubscribeRequest") |  | ||||||
| 	proto.RegisterType((*Message)(nil), "go.micro.broker.Message") |  | ||||||
| 	proto.RegisterMapType((map[string]string)(nil), "go.micro.broker.Message.HeaderEntry") |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func init() { proto.RegisterFile("broker/service/proto/broker.proto", fileDescriptor_df4d8f04292cf3fe) } |  | ||||||
|  |  | ||||||
| var fileDescriptor_df4d8f04292cf3fe = []byte{ |  | ||||||
| 	// 299 bytes of a gzipped FileDescriptorProto |  | ||||||
| 	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0x4d, 0x4b, 0xc3, 0x40, |  | ||||||
| 	0x14, 0xec, 0xb6, 0xb6, 0xa1, 0xaf, 0xa2, 0x65, 0x29, 0x12, 0x7a, 0x31, 0x0d, 0x1e, 0x72, 0xda, |  | ||||||
| 	0x48, 0xbc, 0xa8, 0x88, 0x07, 0xb1, 0xe0, 0x41, 0x41, 0xd6, 0x9b, 0xb7, 0x6c, 0xfa, 0x68, 0x43, |  | ||||||
| 	0x1b, 0x37, 0xdd, 0x4d, 0x0a, 0xf9, 0x23, 0x9e, 0xfc, 0xb1, 0xd2, 0xdd, 0xf8, 0xd5, 0x50, 0x6f, |  | ||||||
| 	0x6f, 0xde, 0xce, 0xce, 0x1b, 0x66, 0x60, 0x22, 0x94, 0x5c, 0xa2, 0x0a, 0x35, 0xaa, 0x4d, 0x9a, |  | ||||||
| 	0x60, 0x98, 0x2b, 0x59, 0xc8, 0xd0, 0x2e, 0x99, 0x01, 0xf4, 0x78, 0x2e, 0x59, 0x96, 0x26, 0x4a, |  | ||||||
| 	0x32, 0xbb, 0xf6, 0x1d, 0xe8, 0x4e, 0xb3, 0xbc, 0xa8, 0xfc, 0x57, 0x38, 0x7a, 0x2e, 0xc5, 0x2a, |  | ||||||
| 	0xd5, 0x0b, 0x8e, 0xeb, 0x12, 0x75, 0x41, 0x47, 0xd0, 0x2d, 0x64, 0x9e, 0x26, 0x2e, 0xf1, 0x48, |  | ||||||
| 	0xd0, 0xe7, 0x16, 0xd0, 0x08, 0x9c, 0x0c, 0xb5, 0x8e, 0xe7, 0xe8, 0xb6, 0x3d, 0x12, 0x0c, 0x22, |  | ||||||
| 	0x97, 0xed, 0x68, 0xb2, 0x27, 0xfb, 0xce, 0xbf, 0x88, 0xfe, 0x2d, 0x0c, 0x5f, 0x4a, 0xa1, 0x13, |  | ||||||
| 	0x95, 0x0a, 0xfc, 0x5f, 0x7d, 0x04, 0xdd, 0x75, 0x89, 0xa5, 0xd5, 0xee, 0x73, 0x0b, 0xfc, 0x77, |  | ||||||
| 	0x02, 0x4e, 0x2d, 0x4a, 0x6f, 0xa0, 0xb7, 0xc0, 0x78, 0x86, 0xca, 0x25, 0x5e, 0x27, 0x18, 0x44, |  | ||||||
| 	0x67, 0xfb, 0xce, 0xb3, 0x07, 0x43, 0x9b, 0xbe, 0x15, 0xaa, 0xe2, 0xf5, 0x1f, 0x4a, 0xe1, 0x40, |  | ||||||
| 	0xc8, 0x59, 0x65, 0xe4, 0x0f, 0xb9, 0x99, 0xc7, 0x57, 0x30, 0xf8, 0x45, 0xa5, 0x43, 0xe8, 0x2c, |  | ||||||
| 	0xb1, 0xaa, 0x6d, 0x6d, 0xc7, 0xad, 0xa9, 0x4d, 0xbc, 0xfa, 0x31, 0x65, 0xc0, 0x75, 0xfb, 0x92, |  | ||||||
| 	0x44, 0x1f, 0x04, 0x7a, 0x77, 0xe6, 0x2a, 0xbd, 0x07, 0xa7, 0xce, 0x8f, 0x9e, 0x36, 0x2c, 0xfd, |  | ||||||
| 	0x4d, 0x76, 0x7c, 0xd2, 0x20, 0xd8, 0x0e, 0x5a, 0xf4, 0x11, 0xfa, 0xdf, 0x49, 0xd1, 0x49, 0x83, |  | ||||||
| 	0xb6, 0x9b, 0xe2, 0x78, 0x6f, 0xf8, 0x7e, 0xeb, 0x9c, 0x88, 0x9e, 0x29, 0xfd, 0xe2, 0x33, 0x00, |  | ||||||
| 	0x00, 0xff, 0xff, 0x19, 0x9f, 0x10, 0x75, 0x19, 0x02, 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 |  | ||||||
|  |  | ||||||
| // BrokerClient is the client API for Broker service. |  | ||||||
| // |  | ||||||
| // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. |  | ||||||
| type BrokerClient interface { |  | ||||||
| 	Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*Empty, error) |  | ||||||
| 	Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (Broker_SubscribeClient, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerClient struct { |  | ||||||
| 	cc *grpc.ClientConn |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewBrokerClient(cc *grpc.ClientConn) BrokerClient { |  | ||||||
| 	return &brokerClient{cc} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *brokerClient) Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*Empty, error) { |  | ||||||
| 	out := new(Empty) |  | ||||||
| 	err := c.cc.Invoke(ctx, "/go.micro.broker.Broker/Publish", in, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *brokerClient) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (Broker_SubscribeClient, error) { |  | ||||||
| 	stream, err := c.cc.NewStream(ctx, &_Broker_serviceDesc.Streams[0], "/go.micro.broker.Broker/Subscribe", opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	x := &brokerSubscribeClient{stream} |  | ||||||
| 	if err := x.ClientStream.SendMsg(in); err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	if err := x.ClientStream.CloseSend(); err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return x, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Broker_SubscribeClient interface { |  | ||||||
| 	Recv() (*Message, error) |  | ||||||
| 	grpc.ClientStream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerSubscribeClient struct { |  | ||||||
| 	grpc.ClientStream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeClient) Recv() (*Message, error) { |  | ||||||
| 	m := new(Message) |  | ||||||
| 	if err := x.ClientStream.RecvMsg(m); err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return m, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // BrokerServer is the server API for Broker service. |  | ||||||
| type BrokerServer interface { |  | ||||||
| 	Publish(context.Context, *PublishRequest) (*Empty, error) |  | ||||||
| 	Subscribe(*SubscribeRequest, Broker_SubscribeServer) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // UnimplementedBrokerServer can be embedded to have forward compatible implementations. |  | ||||||
| type UnimplementedBrokerServer struct { |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (*UnimplementedBrokerServer) Publish(ctx context.Context, req *PublishRequest) (*Empty, error) { |  | ||||||
| 	return nil, status.Errorf(codes.Unimplemented, "method Publish not implemented") |  | ||||||
| } |  | ||||||
| func (*UnimplementedBrokerServer) Subscribe(req *SubscribeRequest, srv Broker_SubscribeServer) error { |  | ||||||
| 	return status.Errorf(codes.Unimplemented, "method Subscribe not implemented") |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func RegisterBrokerServer(s *grpc.Server, srv BrokerServer) { |  | ||||||
| 	s.RegisterService(&_Broker_serviceDesc, srv) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func _Broker_Publish_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { |  | ||||||
| 	in := new(PublishRequest) |  | ||||||
| 	if err := dec(in); err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	if interceptor == nil { |  | ||||||
| 		return srv.(BrokerServer).Publish(ctx, in) |  | ||||||
| 	} |  | ||||||
| 	info := &grpc.UnaryServerInfo{ |  | ||||||
| 		Server:     srv, |  | ||||||
| 		FullMethod: "/go.micro.broker.Broker/Publish", |  | ||||||
| 	} |  | ||||||
| 	handler := func(ctx context.Context, req interface{}) (interface{}, error) { |  | ||||||
| 		return srv.(BrokerServer).Publish(ctx, req.(*PublishRequest)) |  | ||||||
| 	} |  | ||||||
| 	return interceptor(ctx, in, info, handler) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func _Broker_Subscribe_Handler(srv interface{}, stream grpc.ServerStream) error { |  | ||||||
| 	m := new(SubscribeRequest) |  | ||||||
| 	if err := stream.RecvMsg(m); err != nil { |  | ||||||
| 		return err |  | ||||||
| 	} |  | ||||||
| 	return srv.(BrokerServer).Subscribe(m, &brokerSubscribeServer{stream}) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Broker_SubscribeServer interface { |  | ||||||
| 	Send(*Message) error |  | ||||||
| 	grpc.ServerStream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerSubscribeServer struct { |  | ||||||
| 	grpc.ServerStream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeServer) Send(m *Message) error { |  | ||||||
| 	return x.ServerStream.SendMsg(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var _Broker_serviceDesc = grpc.ServiceDesc{ |  | ||||||
| 	ServiceName: "go.micro.broker.Broker", |  | ||||||
| 	HandlerType: (*BrokerServer)(nil), |  | ||||||
| 	Methods: []grpc.MethodDesc{ |  | ||||||
| 		{ |  | ||||||
| 			MethodName: "Publish", |  | ||||||
| 			Handler:    _Broker_Publish_Handler, |  | ||||||
| 		}, |  | ||||||
| 	}, |  | ||||||
| 	Streams: []grpc.StreamDesc{ |  | ||||||
| 		{ |  | ||||||
| 			StreamName:    "Subscribe", |  | ||||||
| 			Handler:       _Broker_Subscribe_Handler, |  | ||||||
| 			ServerStreams: true, |  | ||||||
| 		}, |  | ||||||
| 	}, |  | ||||||
| 	Metadata: "broker/service/proto/broker.proto", |  | ||||||
| } |  | ||||||
| @@ -1,185 +0,0 @@ | |||||||
| // Code generated by protoc-gen-micro. DO NOT EDIT. |  | ||||||
| // source: broker/service/proto/broker.proto |  | ||||||
|  |  | ||||||
| package go_micro_broker |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	fmt "fmt" |  | ||||||
| 	proto "github.com/golang/protobuf/proto" |  | ||||||
| 	math "math" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	context "context" |  | ||||||
| 	api "github.com/micro/go-micro/v2/api" |  | ||||||
| 	client "github.com/micro/go-micro/v2/client" |  | ||||||
| 	server "github.com/micro/go-micro/v2/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 Broker service |  | ||||||
|  |  | ||||||
| func NewBrokerEndpoints() []*api.Endpoint { |  | ||||||
| 	return []*api.Endpoint{} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Client API for Broker service |  | ||||||
|  |  | ||||||
| type BrokerService interface { |  | ||||||
| 	Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error) |  | ||||||
| 	Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerService struct { |  | ||||||
| 	c    client.Client |  | ||||||
| 	name string |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewBrokerService(name string, c client.Client) BrokerService { |  | ||||||
| 	return &brokerService{ |  | ||||||
| 		c:    c, |  | ||||||
| 		name: name, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *brokerService) Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Broker.Publish", in) |  | ||||||
| 	out := new(Empty) |  | ||||||
| 	err := c.c.Call(ctx, req, out, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return out, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (c *brokerService) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error) { |  | ||||||
| 	req := c.c.NewRequest(c.name, "Broker.Subscribe", &SubscribeRequest{}) |  | ||||||
| 	stream, err := c.c.Stream(ctx, req, opts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	if err := stream.Send(in); err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return &brokerServiceSubscribe{stream}, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Broker_SubscribeService interface { |  | ||||||
| 	Context() context.Context |  | ||||||
| 	SendMsg(interface{}) error |  | ||||||
| 	RecvMsg(interface{}) error |  | ||||||
| 	Close() error |  | ||||||
| 	Recv() (*Message, error) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerServiceSubscribe struct { |  | ||||||
| 	stream client.Stream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerServiceSubscribe) Close() error { |  | ||||||
| 	return x.stream.Close() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerServiceSubscribe) Context() context.Context { |  | ||||||
| 	return x.stream.Context() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerServiceSubscribe) SendMsg(m interface{}) error { |  | ||||||
| 	return x.stream.Send(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerServiceSubscribe) RecvMsg(m interface{}) error { |  | ||||||
| 	return x.stream.Recv(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerServiceSubscribe) Recv() (*Message, error) { |  | ||||||
| 	m := new(Message) |  | ||||||
| 	err := x.stream.Recv(m) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
| 	return m, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Server API for Broker service |  | ||||||
|  |  | ||||||
| type BrokerHandler interface { |  | ||||||
| 	Publish(context.Context, *PublishRequest, *Empty) error |  | ||||||
| 	Subscribe(context.Context, *SubscribeRequest, Broker_SubscribeStream) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func RegisterBrokerHandler(s server.Server, hdlr BrokerHandler, opts ...server.HandlerOption) error { |  | ||||||
| 	type broker interface { |  | ||||||
| 		Publish(ctx context.Context, in *PublishRequest, out *Empty) error |  | ||||||
| 		Subscribe(ctx context.Context, stream server.Stream) error |  | ||||||
| 	} |  | ||||||
| 	type Broker struct { |  | ||||||
| 		broker |  | ||||||
| 	} |  | ||||||
| 	h := &brokerHandler{hdlr} |  | ||||||
| 	return s.Handle(s.NewHandler(&Broker{h}, opts...)) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerHandler struct { |  | ||||||
| 	BrokerHandler |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *brokerHandler) Publish(ctx context.Context, in *PublishRequest, out *Empty) error { |  | ||||||
| 	return h.BrokerHandler.Publish(ctx, in, out) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (h *brokerHandler) Subscribe(ctx context.Context, stream server.Stream) error { |  | ||||||
| 	m := new(SubscribeRequest) |  | ||||||
| 	if err := stream.Recv(m); err != nil { |  | ||||||
| 		return err |  | ||||||
| 	} |  | ||||||
| 	return h.BrokerHandler.Subscribe(ctx, m, &brokerSubscribeStream{stream}) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type Broker_SubscribeStream interface { |  | ||||||
| 	Context() context.Context |  | ||||||
| 	SendMsg(interface{}) error |  | ||||||
| 	RecvMsg(interface{}) error |  | ||||||
| 	Close() error |  | ||||||
| 	Send(*Message) error |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type brokerSubscribeStream struct { |  | ||||||
| 	stream server.Stream |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeStream) Close() error { |  | ||||||
| 	return x.stream.Close() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeStream) Context() context.Context { |  | ||||||
| 	return x.stream.Context() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeStream) SendMsg(m interface{}) error { |  | ||||||
| 	return x.stream.Send(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeStream) RecvMsg(m interface{}) error { |  | ||||||
| 	return x.stream.Recv(m) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (x *brokerSubscribeStream) Send(m *Message) error { |  | ||||||
| 	return x.stream.Send(m) |  | ||||||
| } |  | ||||||
| @@ -1,25 +0,0 @@ | |||||||
| syntax = "proto3"; |  | ||||||
|  |  | ||||||
| package go.micro.broker; |  | ||||||
|  |  | ||||||
| service Broker { |  | ||||||
| 	rpc Publish(PublishRequest) returns (Empty) {}; |  | ||||||
| 	rpc Subscribe(SubscribeRequest) returns (stream Message) {}; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Empty {} |  | ||||||
|  |  | ||||||
| message PublishRequest { |  | ||||||
| 	string topic = 1; |  | ||||||
| 	Message message = 2; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message SubscribeRequest { |  | ||||||
| 	string topic = 1; |  | ||||||
| 	string queue = 2; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| message Message { |  | ||||||
| 	map<string,string> header = 1; |  | ||||||
| 	bytes body = 2; |  | ||||||
| } |  | ||||||
| @@ -1,146 +0,0 @@ | |||||||
| // Package service provides the broker service client |  | ||||||
| package service |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"time" |  | ||||||
|  |  | ||||||
| 	"github.com/micro/go-micro/v2/broker" |  | ||||||
| 	pb "github.com/micro/go-micro/v2/broker/service/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/client" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| type serviceBroker struct { |  | ||||||
| 	Addrs   []string |  | ||||||
| 	Client  pb.BrokerService |  | ||||||
| 	options broker.Options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var ( |  | ||||||
| 	DefaultName = "go.micro.broker" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Address() string { |  | ||||||
| 	return b.Addrs[0] |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Connect() error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Disconnect() error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Init(opts ...broker.Option) error { |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&b.options) |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Options() broker.Options { |  | ||||||
| 	return b.options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { |  | ||||||
| 	if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 		logger.Debugf("Publishing to topic %s broker %v", topic, b.Addrs) |  | ||||||
| 	} |  | ||||||
| 	_, err := b.Client.Publish(context.TODO(), &pb.PublishRequest{ |  | ||||||
| 		Topic: topic, |  | ||||||
| 		Message: &pb.Message{ |  | ||||||
| 			Header: msg.Header, |  | ||||||
| 			Body:   msg.Body, |  | ||||||
| 		}, |  | ||||||
| 	}, client.WithAddress(b.Addrs...)) |  | ||||||
| 	return err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { |  | ||||||
| 	var options broker.SubscribeOptions |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 		logger.Debugf("Subscribing to topic %s queue %s broker %v", topic, options.Queue, b.Addrs) |  | ||||||
| 	} |  | ||||||
| 	stream, err := b.Client.Subscribe(context.TODO(), &pb.SubscribeRequest{ |  | ||||||
| 		Topic: topic, |  | ||||||
| 		Queue: options.Queue, |  | ||||||
| 	}, client.WithAddress(b.Addrs...), client.WithRequestTimeout(time.Hour)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	sub := &serviceSub{ |  | ||||||
| 		topic:   topic, |  | ||||||
| 		queue:   options.Queue, |  | ||||||
| 		handler: handler, |  | ||||||
| 		stream:  stream, |  | ||||||
| 		closed:  make(chan bool), |  | ||||||
| 		options: options, |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	go func() { |  | ||||||
| 		for { |  | ||||||
| 			select { |  | ||||||
| 			case <-sub.closed: |  | ||||||
| 				if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 					logger.Debugf("Unsubscribed from topic %s", topic) |  | ||||||
| 				} |  | ||||||
| 				return |  | ||||||
| 			default: |  | ||||||
| 				if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 					// run the subscriber |  | ||||||
| 					logger.Debugf("Streaming from broker %v to topic [%s] queue [%s]", b.Addrs, topic, options.Queue) |  | ||||||
| 				} |  | ||||||
| 				if err := sub.run(); err != nil { |  | ||||||
| 					if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 						logger.Debugf("Resubscribing to topic %s broker %v", topic, b.Addrs) |  | ||||||
| 					} |  | ||||||
| 					stream, err := b.Client.Subscribe(context.TODO(), &pb.SubscribeRequest{ |  | ||||||
| 						Topic: topic, |  | ||||||
| 						Queue: options.Queue, |  | ||||||
| 					}, client.WithAddress(b.Addrs...), client.WithRequestTimeout(time.Hour)) |  | ||||||
| 					if err != nil { |  | ||||||
| 						if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 							logger.Debugf("Failed to resubscribe to topic %s: %v", topic, err) |  | ||||||
| 						} |  | ||||||
| 						time.Sleep(time.Second) |  | ||||||
| 						continue |  | ||||||
| 					} |  | ||||||
| 					// new stream |  | ||||||
| 					sub.stream = stream |  | ||||||
| 				} |  | ||||||
| 			} |  | ||||||
| 		} |  | ||||||
| 	}() |  | ||||||
|  |  | ||||||
| 	return sub, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (b *serviceBroker) String() string { |  | ||||||
| 	return "service" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewBroker(opts ...broker.Option) broker.Broker { |  | ||||||
| 	var options broker.Options |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	addrs := options.Addrs |  | ||||||
| 	if len(addrs) == 0 { |  | ||||||
| 		addrs = []string{"127.0.0.1:8001"} |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	cli := client.DefaultClient |  | ||||||
|  |  | ||||||
| 	return &serviceBroker{ |  | ||||||
| 		Addrs:   addrs, |  | ||||||
| 		Client:  pb.NewBrokerService(DefaultName, cli), |  | ||||||
| 		options: options, |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
| @@ -1,108 +0,0 @@ | |||||||
| package service |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"github.com/micro/go-micro/v2/broker" |  | ||||||
| 	pb "github.com/micro/go-micro/v2/broker/service/proto" |  | ||||||
| 	"github.com/micro/go-micro/v2/logger" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| type serviceSub struct { |  | ||||||
| 	topic   string |  | ||||||
| 	queue   string |  | ||||||
| 	handler broker.Handler |  | ||||||
| 	stream  pb.Broker_SubscribeService |  | ||||||
| 	closed  chan bool |  | ||||||
| 	options broker.SubscribeOptions |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type serviceEvent struct { |  | ||||||
| 	topic   string |  | ||||||
| 	err     error |  | ||||||
| 	message *broker.Message |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceEvent) Topic() string { |  | ||||||
| 	return s.topic |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceEvent) Message() *broker.Message { |  | ||||||
| 	return s.message |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceEvent) Ack() error { |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceEvent) Error() error { |  | ||||||
| 	return s.err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceSub) isClosed() bool { |  | ||||||
| 	select { |  | ||||||
| 	case <-s.closed: |  | ||||||
| 		return true |  | ||||||
| 	default: |  | ||||||
| 		return false |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceSub) run() error { |  | ||||||
| 	exit := make(chan bool) |  | ||||||
| 	go func() { |  | ||||||
| 		select { |  | ||||||
| 		case <-exit: |  | ||||||
| 		case <-s.closed: |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		// close the stream |  | ||||||
| 		s.stream.Close() |  | ||||||
| 	}() |  | ||||||
|  |  | ||||||
| 	for { |  | ||||||
| 		// TODO: do not fail silently |  | ||||||
| 		msg, err := s.stream.Recv() |  | ||||||
| 		if err != nil { |  | ||||||
| 			if logger.V(logger.DebugLevel, logger.DefaultLogger) { |  | ||||||
| 				logger.Debugf("Streaming error for subcription to topic %s: %v", s.Topic(), err) |  | ||||||
| 			} |  | ||||||
|  |  | ||||||
| 			// close the exit channel |  | ||||||
| 			close(exit) |  | ||||||
|  |  | ||||||
| 			// don't return an error if we unsubscribed |  | ||||||
| 			if s.isClosed() { |  | ||||||
| 				return nil |  | ||||||
| 			} |  | ||||||
|  |  | ||||||
| 			// return stream error |  | ||||||
| 			return err |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		p := &serviceEvent{ |  | ||||||
| 			topic: s.topic, |  | ||||||
| 			message: &broker.Message{ |  | ||||||
| 				Header: msg.Header, |  | ||||||
| 				Body:   msg.Body, |  | ||||||
| 			}, |  | ||||||
| 		} |  | ||||||
| 		p.err = s.handler(p) |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceSub) Options() broker.SubscribeOptions { |  | ||||||
| 	return s.options |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceSub) Topic() string { |  | ||||||
| 	return s.topic |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *serviceSub) Unsubscribe() error { |  | ||||||
| 	select { |  | ||||||
| 	case <-s.closed: |  | ||||||
| 		return nil |  | ||||||
| 	default: |  | ||||||
| 		close(s.closed) |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
							
								
								
									
										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 | ||||||
|  | } | ||||||
							
								
								
									
										29
									
								
								cache/cache.go
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								cache/cache.go
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,29 @@ | |||||||
|  | // 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 | ||||||
|  | 	} | ||||||
|  | } | ||||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user