├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── main.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── api-spec ├── hooks.js └── payment.json ├── cmd └── paymentsvc │ └── main.go ├── component_test.go ├── docker-compose-zipkin.yml ├── docker-compose.yml ├── docker └── payment │ ├── Dockerfile │ └── Dockerfile-release ├── endpoints.go ├── logging.go ├── scripts ├── build.sh └── push.sh ├── service.go ├── service_test.go ├── test ├── Dockerfile ├── container.py ├── test.sh ├── unit.py └── util │ ├── Api.py │ ├── Docker.py │ ├── Dredd.py │ └── __init__.py ├── transport.go ├── vendor └── manifest └── wiring.go /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | We'd love to accept your contributions; large or small. Simply submit an issue or pull request via Github and involve one of the active members. Simple! But please read the rest of this document to ensure we're all on the same page. 4 | 5 | ## General Rules 6 | 7 | - Be kind and polite. Written language often does not convey the sentiment, so make sure you use lots of jokes and emoticons to get the sentiment across. 8 | - Prefer best practice. Everyone has their preferred style, but try to conform to current best practices. We don't enforce any strict rules. 9 | - Test your code to the best of your abilities. See the testing documentation for the correct scope of your test. 10 | 11 | ## Bug reports or feature requests 12 | 13 | Please open an issue if you have found an issue or have an idea for a new feature. Please follow the bug reporting guidelines if you submit an issue. 14 | 15 | ## New Contributors 16 | 17 | We have a list of issues on Github with "HelpWanted" labels attributed to them. These represent tasks that we don't have time to do, are self-contained and relatively easy to implement. If you'd like to contribute, but don't know where to start, [look here](https://github.com/microservices-demo/microservices-demo/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20label%3AHelpWanted). 18 | 19 | ## Direction 20 | 21 | This project does have a general direction, but we're happy to consider deviating or pivoting from the direction we're currently heading. See the introductory material for details regarding direction. 22 | 23 | With that said, there is absolutely nothing stopping you from submitting a PR. If you've taken the effort to contribute, someone will make the effort to review. 24 | 25 | ## License 26 | 27 | This project is Apache v2.0 licenced. Submitting and merging a PR implies you accept these terms. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | - Add labels appropriate to the issue 2 | - Describe the expected behaviour and the actual behaviour 3 | - Describe steps to reproduce the problem 4 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | - Read the contribution guidelines 2 | - Include a reference to a related issue in this repository 3 | - A description of the changes proposed in the pull request -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | branches: 6 | - "*" # run for branches 7 | tags: 8 | - "*" # run for tags 9 | pull_request: 10 | branches: 11 | - "*" # run for branches 12 | tags: 13 | - "*" # run for tags 14 | 15 | 16 | jobs: 17 | test: 18 | defaults: 19 | run: 20 | working-directory: go/src/github.com/microservices-demo/payment 21 | runs-on: ubuntu-latest 22 | env: 23 | GROUP: weaveworksdemos 24 | COMMIT: ${{ github.sha }} 25 | REPO: payment 26 | GO_VERSION: 1.7 27 | GOPATH: /home/runner/work/payment/payment/go/ 28 | steps: 29 | - uses: actions/checkout@v2 30 | with: 31 | fetch-depth: 1 32 | path: go/src/github.com/microservices-demo/payment 33 | 34 | 35 | # 36 | # 37 | # Set up go 38 | - uses: actions/setup-go@v2 39 | with: 40 | go-version: ${{ env.GO_VERSION }} # The Go version to download (if necessary) and use. 41 | 42 | # 43 | # 44 | # Install prereqs 45 | - name: Install prereqs 46 | run: | 47 | go get -u github.com/mattn/goveralls 48 | go get -u github.com/FiloSottile/gvt 49 | gvt restore 50 | 51 | # 52 | # 53 | # Container build step 54 | - name: Build 55 | env: 56 | DOCKER_BUILDKIT: 1 57 | run: ./scripts/build.sh 58 | 59 | # 60 | # 61 | # Unit test step 62 | - name: Unit test 63 | env: 64 | DOCKER_BUILDKIT: 1 65 | run: ./test/test.sh unit.py 66 | 67 | # 68 | # 69 | # Container test step 70 | - name: Container test 71 | env: 72 | DOCKER_BUILDKIT: 1 73 | run: ./test/test.sh container.py --tag ${{ env.COMMIT }} 74 | 75 | # 76 | # 77 | # Submit coveralls 78 | - name: Submit Coveralls 79 | env: 80 | COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }} 81 | run: goveralls -coverprofile=coverage.out -service=github 82 | 83 | # 84 | # 85 | # Push to dockerhub 86 | - name: Push to Docker Hub 87 | uses: docker/build-push-action@v1 88 | if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master' 89 | with: 90 | dockerfile: go/src/github.com/microservices-demo/payment/docker/payment/Dockerfile-release 91 | path: go/src/github.com/microservices-demo/payment/docker/payment 92 | username: ${{ secrets.DOCKER_USER }} 93 | password: ${{ secrets.DOCKER_PASS }} 94 | repository: ${{ env.GROUP }}/${{ env.REPO }} 95 | tag_with_ref: true 96 | tag_with_sha: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Dependency directories 7 | node_modules 8 | jspm_packages 9 | 10 | # Optional npm cache directory 11 | .npm 12 | 13 | ### Go template 14 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 15 | *.o 16 | *.a 17 | *.so 18 | 19 | # Folders 20 | _obj 21 | _test 22 | 23 | # Architecture specific extensions/prefixes 24 | *.[568vq] 25 | [568vq].out 26 | 27 | *.cgo1.go 28 | *.cgo2.c 29 | _cgo_defun.c 30 | _cgo_gotypes.go 31 | _cgo_export.* 32 | 33 | _testmain.go 34 | 35 | *.exe 36 | *.test 37 | *.prof 38 | ### Java template 39 | /target/ 40 | *.class 41 | 42 | # Mobile Tools for Java (J2ME) 43 | .mtj.tmp/ 44 | 45 | # Package Files # 46 | *.war 47 | *.ear 48 | 49 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 50 | hs_err_pid* 51 | ### OSX template 52 | .DS_Store 53 | .AppleDouble 54 | .LSOverride 55 | 56 | # Icon must end with two \r 57 | Icon 58 | 59 | # Thumbnails 60 | ._* 61 | 62 | # Files that might appear in the root of a volume 63 | .DocumentRevisions-V100 64 | .fseventsd 65 | .Spotlight-V100 66 | .TemporaryItems 67 | .Trashes 68 | .VolumeIcon.icns 69 | 70 | # Directories potentially created on remote AFP share 71 | .AppleDB 72 | .AppleDesktop 73 | Network Trash Folder 74 | Temporary Items 75 | .apdisk 76 | ### JetBrains template 77 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 78 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 79 | 80 | # User-specific stuff: 81 | .idea 82 | 83 | ## File-based project format: 84 | *.iws 85 | *.iml 86 | 87 | ## Plugin-specific files: 88 | 89 | # IntelliJ 90 | /out/ 91 | 92 | # mpeltonen/sbt-idea plugin 93 | .idea_modules/ 94 | 95 | # JIRA plugin 96 | atlassian-ide-plugin.xml 97 | 98 | # Crashlytics plugin (for Android Studio and IntelliJ) 99 | com_crashlytics_export_strings.xml 100 | crashlytics.properties 101 | crashlytics-build.properties 102 | fabric.properties 103 | # Created by .ignore support plugin (hsz.mobi) 104 | 105 | # Maven builds 106 | */target 107 | */*/target 108 | 109 | # AWS ECS install scripts generates an SSH key file 110 | weave-ecs-demo-key.pem 111 | 112 | # Load test generates pyc files 113 | *.pyc 114 | 115 | # Ignore Vagrant cache files 116 | *.vagrant/ 117 | 118 | # Ignore coverage reports 119 | coverage/ 120 | 121 | # Tern 122 | .tern-port 123 | docker/payment 124 | vendor/** 125 | !vendor/manifest 126 | coverage.out 127 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: required 3 | services: 4 | - docker 5 | go: 6 | - 1.7 7 | before_install: 8 | - go get -u github.com/mattn/goveralls 9 | - go get -u github.com/FiloSottile/gvt 10 | - gvt restore 11 | install: true 12 | env: 13 | - GROUP=weaveworksdemos COMMIT=$TRAVIS_COMMIT TAG=$TRAVIS_TAG REPO=payment; 14 | script: 15 | - set -e 16 | - "make test" 17 | after_success: 18 | - set -e; 19 | - if [ -z "$DOCKER_PASS" ] ; then echo "This is a build triggered by an external PR. 20 | Skipping docker push."; exit 0; fi; 21 | - docker login -u $DOCKER_USER -p $DOCKER_PASS; 22 | - "./scripts/push.sh" 23 | - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci 24 | notifications: 25 | slack: 26 | secure: cRuwjAXZg1i/1qqQeeIe/Q0WmNE/WKOBvG+IWz/EDE/8sJBx67TugGIovCqW9J4VZX5hpzhGbnWV2535/+aHihbaquQ+2kO81EJaILD7MUoi2mxoIHH0KoMe/nYnI/Grdjv6+JbqybLfK3nQfq7sBQDbG8Qi4b7IcO2Bxg5Q9vUsRzJ1/NYNdDk/coEPlEDs+R0WqxmEFmVGDlZvbzNyMEzokkZIW+xEu8T9Qjr51Jn84zfQ1J46+y/ZNLKI+5oScX6JI4a2cYEopfwX2lQREl1YuL+NyuQw0jJy/mxtkai501XTiht7XOYbI+kmwj9+NIGQWGHlXSD7Q4Nrd/0MdMaAlUXxb+xlZ4uY1IpZnMfWT4nIe1SIr3hnwtIOrVcEwrElWvhm3dk3Lmrz46v0JUXkYh4DxEnMucYon0Q+4EoNRHFQWMSeKQNXrZocxu/DMTgiISUsE3lmqbL7SKMV27wDgyGaiWqgmMcmbR6d/gOilbbLoK9L2wtRaqPMpk4lAoIyzxt+EIs/iT73UHV3lz3/7a3QuIwC3T4BqwykT+8ioUW9QBlB8OeW2QQxIerxAGD+/Rwlb3+mAvnqqPfkXMoyEu+0MPuQg4hA/+ZXba9wivZMk57AM14hJO9EPYhcsf6V8FJHn8WDdCKGW95Kp8el5eJ22V2mIUQ5WLygReM= 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | NAME = weaveworksdemos/payment 2 | INSTANCE = payment 3 | 4 | .PHONY: default copy test 5 | 6 | default: test 7 | 8 | copy: 9 | docker create --name $(INSTANCE) $(NAME)-dev 10 | docker cp $(INSTANCE):/app $(shell pwd)/app 11 | docker rm $(INSTANCE) 12 | 13 | release: 14 | docker build -t $(NAME) -f ./docker/payment/Dockerfile-release . 15 | 16 | test: 17 | GROUP=weaveworksdemos COMMIT=$(COMMIT) ./scripts/build.sh 18 | ./test/test.sh unit.py 19 | ./test/test.sh container.py --tag $(COMMIT) 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATED: Payment 2 | [![Build Status](https://travis-ci.org/microservices-demo/payment.svg?branch=master)](https://travis-ci.org/microservices-demo/payment) 3 | [![Coverage Status](https://coveralls.io/repos/github/microservices-demo/payment/badge.svg?branch=master)](https://coveralls.io/github/microservices-demo/payment?branch=master) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/microservices-demo/user)](https://goreportcard.com/report/github.com/microservices-demo/user) 5 | [![](https://images.microbadger.com/badges/image/weaveworksdemos/payment.svg)](http://microbadger.com/images/weaveworksdemos/payment "Get your own image badge on microbadger.com") 6 | 7 | A microservices-demo service that provides payment services. 8 | This build is built, tested and released by travis. 9 | 10 | ## Bugs, Feature Requests and Contributing 11 | We'd love to see community contributions. We like to keep it simple and use Github issues to track bugs and feature requests and pull requests to manage contributions. 12 | 13 | ## API Spec 14 | 15 | Checkout the API Spec [here](http://microservices-demo.github.io/api/index?url=https://raw.githubusercontent.com/microservices-demo/payment/master/api-spec/payment.json) 16 | 17 | ## Build 18 | 19 | #### Dependencies 20 | ``` 21 | cd $GOPATH/src/github.com/microservices-demo/payment/ 22 | go get -u github.com/FiloSottile/gvt 23 | gvt restore 24 | ``` 25 | 26 | #### Using native Go tools 27 | In order to build the project locally you need to make sure that the repository directory is located in the correct 28 | $GOPATH directory: $GOPATH/src/github.com/microservices-demo/payment/. Once that is in place you can build by running: 29 | 30 | ``` 31 | cd $GOPATH/src/github.com/microservices-demo/payment/paymentsvc/ 32 | go build -o payment 33 | ``` 34 | 35 | The result is a binary named `payment`, in the current directory. 36 | 37 | #### Using Docker Compose 38 | `docker-compose build` 39 | 40 | ## Test 41 | `COMMIT=test make test` 42 | 43 | ## Run 44 | 45 | #### Using Go native 46 | 47 | If you followed to Go build instructions, you should have a "payment" binary in $GOPATH/src/github.com/microservices-demo/payment/cmd/paymentsvc/. 48 | To run it use: 49 | ``` 50 | ./payment 51 | ts=2016-12-14T11:48:58Z caller=main.go:29 transport=HTTP port=8080 52 | ``` 53 | 54 | #### Using Docker Compose 55 | 56 | If you used Docker Compose to build the payment project, the result should be a Docker image called `weaveworksdemos/payment`. 57 | To run it use: 58 | ``` 59 | docker-compose up 60 | ``` 61 | 62 | You can now access the service via http://localhost:8082 63 | 64 | ## Check 65 | 66 | You can check the health of the service by doing a GET request to the health endpoint: 67 | 68 | ``` 69 | curl http://localhost:8082/health 70 | {"health":[{"service":"payment","status":"OK","time":"2016-12-14 12:22:04.716316395 +0000 UTC"}]} 71 | ``` 72 | 73 | ## Use 74 | 75 | You can authorise a payment by POSTing to the paymentAuth endpoint: 76 | 77 | ``` 78 | curl -H "Content-Type: application/json" -X POST -d'{"Amount":40}' http://localhost:8082/paymentAuth 79 | {"authorised":true} 80 | ``` 81 | 82 | ## Push 83 | `GROUP=weaveworksdemos COMMIT=test ./scripts/push.sh` 84 | -------------------------------------------------------------------------------- /api-spec/hooks.js: -------------------------------------------------------------------------------- 1 | const hooks = require('hooks'); 2 | 3 | // Setup database connection before Dredd starts testing 4 | hooks.before("/paymentAuth > POST", function(transaction, done) { 5 | transaction.request.headers['Content-Type'] = 'application/json'; 6 | transaction.request.body = JSON.stringify({ 7 | "amount": 10.00 8 | }); 9 | done(); 10 | }); 11 | -------------------------------------------------------------------------------- /api-spec/payment.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "", 5 | "title": "Payment", 6 | "description": "Payment service spec", 7 | "license": { 8 | "name": "MIT", 9 | "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" 10 | } 11 | }, 12 | "host": "payment", 13 | "basePath": "/", 14 | "securityDefinitions": {}, 15 | "schemes": [ 16 | "http" 17 | ], 18 | "consumes": [ 19 | "application/json; charset=utf-8" 20 | ], 21 | "produces": [ 22 | "application/json; charset=utf-8" 23 | ], 24 | "paths": { 25 | "/health": { 26 | "get": { 27 | "description": "", 28 | "operationId": "/health > GET", 29 | "produces": [ 30 | "application/json; charset=utf-8" 31 | ], 32 | "parameters": [], 33 | "responses": { 34 | "200": { 35 | "description": "", 36 | "schema": { 37 | "$ref": "#/definitions/health" 38 | } 39 | } 40 | } 41 | } 42 | }, 43 | "/paymentAuth": { 44 | "post": { 45 | "description": "Payment authorisation", 46 | "operationId": "/paymentAuth > POST", 47 | "produces": [ 48 | "application/json; charset=utf-8" 49 | ], 50 | "responses": { 51 | "200": { 52 | "description": "", 53 | "schema": { 54 | "$ref": "#/definitions/paymentAuth" 55 | } 56 | } 57 | } 58 | 59 | } 60 | } 61 | }, 62 | "definitions": { 63 | "health": { 64 | "title": "Health", 65 | "type": "object", 66 | "properties": { 67 | "health": { 68 | "type": "array", 69 | "items": { 70 | "type": "object", 71 | "properties": { 72 | "service": { 73 | "type": "string" 74 | }, 75 | "status": { 76 | "type": "string" 77 | }, 78 | "time": { 79 | "type": "string" 80 | } 81 | } 82 | } 83 | } 84 | }, 85 | "required": [ 86 | "health" 87 | ] 88 | }, 89 | "paymentAuth": { 90 | "title": "paymentAuth response", 91 | "type": "object", 92 | "properties": { 93 | "authorised": { 94 | "type": "boolean" 95 | } 96 | }, 97 | "required": [ 98 | "authorised" 99 | ] 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /cmd/paymentsvc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "net" 7 | "net/http" 8 | "os" 9 | "os/signal" 10 | "strings" 11 | "syscall" 12 | 13 | "github.com/go-kit/kit/log" 14 | "github.com/microservices-demo/payment" 15 | stdopentracing "github.com/opentracing/opentracing-go" 16 | zipkin "github.com/openzipkin/zipkin-go-opentracing" 17 | "golang.org/x/net/context" 18 | ) 19 | 20 | const ( 21 | ServiceName = "payment" 22 | ) 23 | 24 | func main() { 25 | var ( 26 | port = flag.String("port", "8080", "Port to bind HTTP listener") 27 | zip = flag.String("zipkin", os.Getenv("ZIPKIN"), "Zipkin address") 28 | declineAmount = flag.Float64("decline", 105, "Decline payments over certain amount") 29 | ) 30 | flag.Parse() 31 | var tracer stdopentracing.Tracer 32 | { 33 | // Log domain. 34 | var logger log.Logger 35 | { 36 | logger = log.NewLogfmtLogger(os.Stderr) 37 | logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC) 38 | logger = log.NewContext(logger).With("caller", log.DefaultCaller) 39 | } 40 | // Find service local IP. 41 | conn, err := net.Dial("udp", "8.8.8.8:80") 42 | if err != nil { 43 | logger.Log("err", err) 44 | os.Exit(1) 45 | } 46 | localAddr := conn.LocalAddr().(*net.UDPAddr) 47 | host := strings.Split(localAddr.String(), ":")[0] 48 | defer conn.Close() 49 | if *zip == "" { 50 | tracer = stdopentracing.NoopTracer{} 51 | } else { 52 | logger := log.NewContext(logger).With("tracer", "Zipkin") 53 | logger.Log("addr", zip) 54 | collector, err := zipkin.NewHTTPCollector( 55 | *zip, 56 | zipkin.HTTPLogger(logger), 57 | ) 58 | if err != nil { 59 | logger.Log("err", err) 60 | os.Exit(1) 61 | } 62 | tracer, err = zipkin.NewTracer( 63 | zipkin.NewRecorder(collector, false, fmt.Sprintf("%v:%v", host, port), ServiceName), 64 | ) 65 | if err != nil { 66 | logger.Log("err", err) 67 | os.Exit(1) 68 | } 69 | } 70 | stdopentracing.InitGlobalTracer(tracer) 71 | 72 | } 73 | // Mechanical stuff. 74 | errc := make(chan error) 75 | ctx := context.Background() 76 | 77 | handler, logger := payment.WireUp(ctx, float32(*declineAmount), tracer, ServiceName) 78 | 79 | // Create and launch the HTTP server. 80 | go func() { 81 | logger.Log("transport", "HTTP", "port", *port) 82 | errc <- http.ListenAndServe(":"+*port, handler) 83 | }() 84 | 85 | // Capture interrupts. 86 | go func() { 87 | c := make(chan os.Signal) 88 | signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) 89 | errc <- fmt.Errorf("%s", <-c) 90 | }() 91 | 92 | logger.Log("exit", <-errc) 93 | } 94 | -------------------------------------------------------------------------------- /component_test.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "io/ioutil" 7 | "net/http" 8 | "net/http/httptest" 9 | "testing" 10 | 11 | "github.com/opentracing/opentracing-go" 12 | "golang.org/x/net/context" 13 | ) 14 | 15 | func TestComponent(t *testing.T) { 16 | // Mechanical stuff. 17 | ctx := context.Background() 18 | 19 | handler, logger := WireUp(ctx, float32(99.99), opentracing.GlobalTracer(), "test") 20 | 21 | ts := httptest.NewServer(handler) 22 | defer ts.Close() 23 | 24 | var request AuthoriseRequest 25 | request.Amount = 9.99 26 | requestBytes, err := json.Marshal(request) 27 | if err != nil { 28 | t.Fatal("ERROR", err) 29 | } 30 | 31 | res, err := http.Post(ts.URL+"/paymentAuth", "application/json", bytes.NewReader(requestBytes)) 32 | if err != nil { 33 | t.Fatal("ERROR", err) 34 | } 35 | greeting, err := ioutil.ReadAll(res.Body) 36 | res.Body.Close() 37 | if err != nil { 38 | t.Fatal("ERROR", err) 39 | } 40 | var response Authorisation 41 | json.Unmarshal(greeting, &response) 42 | 43 | logger.Log("Authorised", response.Authorised) 44 | 45 | expected := true 46 | if response.Authorised != expected { 47 | t.Errorf("Authorise returned unexpected result: got %v expected %v", 48 | response.Authorised, expected) 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /docker-compose-zipkin.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | payment: 5 | image: weaveworksdemos/payment 6 | hostname: payment 7 | restart: always 8 | cap_drop: 9 | - all 10 | cap_add: 11 | - NET_BIND_SERVICE 12 | read_only: true 13 | environment: 14 | - reschedule=on-node-failure 15 | - ZIPKIN=http://zipkin:9411/api/v1/spans 16 | ports: 17 | - "8082:80" 18 | zipkin: 19 | image: openzipkin/zipkin 20 | hostname: zipkin 21 | restart: always 22 | cap_drop: 23 | - all 24 | cap_add: 25 | - CHOWN 26 | - SETGID 27 | - SETUID 28 | read_only: true 29 | tmpfs: 30 | - /tmp:rw,noexec,nosuid 31 | environment: 32 | - reschedule=on-node-failure 33 | ports: 34 | - "9411:9411" 35 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | payment: 5 | build: 6 | context: . 7 | dockerfile: docker/payment/Dockerfile 8 | image: weaveworksdemos/payment 9 | hostname: payment 10 | restart: always 11 | cap_drop: 12 | - all 13 | cap_add: 14 | - NET_BIND_SERVICE 15 | read_only: true 16 | ports: 17 | - "8082:80" 18 | -------------------------------------------------------------------------------- /docker/payment/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.7 2 | 3 | COPY . /go/src/github.com/microservices-demo/payment/ 4 | 5 | RUN go get -u github.com/FiloSottile/gvt 6 | RUN cd /go/src/github.com/microservices-demo/payment/ && gvt restore 7 | 8 | RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o /app github.com/microservices-demo/payment/cmd/paymentsvc 9 | 10 | FROM alpine:3.4 11 | 12 | WORKDIR / 13 | COPY --from=0 /app /app 14 | 15 | ENV SERVICE_USER=myuser \ 16 | SERVICE_UID=10001 \ 17 | SERVICE_GROUP=mygroup \ 18 | SERVICE_GID=10001 19 | 20 | RUN addgroup -g ${SERVICE_GID} ${SERVICE_GROUP} && \ 21 | adduser -g "${SERVICE_NAME} user" -D -H -G ${SERVICE_GROUP} -s /sbin/nologin -u ${SERVICE_UID} ${SERVICE_USER} && \ 22 | chmod +x /app && \ 23 | chown -R ${SERVICE_USER}:${SERVICE_GROUP} /app 24 | 25 | USER ${SERVICE_USER} 26 | 27 | CMD ["/app", "-port=8080"] 28 | 29 | EXPOSE 8080 30 | -------------------------------------------------------------------------------- /docker/payment/Dockerfile-release: -------------------------------------------------------------------------------- 1 | FROM alpine:3.4 2 | 3 | WORKDIR / 4 | COPY app / 5 | 6 | ENV SERVICE_USER=myuser \ 7 | SERVICE_UID=10001 \ 8 | SERVICE_GROUP=mygroup \ 9 | SERVICE_GID=10001 10 | 11 | RUN addgroup -g ${SERVICE_GID} ${SERVICE_GROUP} && \ 12 | adduser -g "${SERVICE_NAME} user" -D -H -G ${SERVICE_GROUP} -s /sbin/nologin -u ${SERVICE_UID} ${SERVICE_USER} && \ 13 | chmod +x /app && \ 14 | chown -R ${SERVICE_USER}:${SERVICE_GROUP} /app 15 | 16 | USER ${SERVICE_USER} 17 | 18 | CMD ["/app", "-port=8080"] 19 | 20 | EXPOSE 8080 21 | -------------------------------------------------------------------------------- /endpoints.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "github.com/go-kit/kit/endpoint" 5 | "github.com/go-kit/kit/tracing/opentracing" 6 | stdopentracing "github.com/opentracing/opentracing-go" 7 | "golang.org/x/net/context" 8 | ) 9 | 10 | // Endpoints collects the endpoints that comprise the Service. 11 | type Endpoints struct { 12 | AuthoriseEndpoint endpoint.Endpoint 13 | HealthEndpoint endpoint.Endpoint 14 | } 15 | 16 | // MakeEndpoints returns an Endpoints structure, where each endpoint is 17 | // backed by the given service. 18 | func MakeEndpoints(s Service, tracer stdopentracing.Tracer) Endpoints { 19 | return Endpoints{ 20 | AuthoriseEndpoint: opentracing.TraceServer(tracer, "POST /paymentAuth")(MakeAuthoriseEndpoint(s)), 21 | HealthEndpoint: opentracing.TraceServer(tracer, "GET /health")(MakeHealthEndpoint(s)), 22 | } 23 | } 24 | 25 | // MakeListEndpoint returns an endpoint via the given service. 26 | func MakeAuthoriseEndpoint(s Service) endpoint.Endpoint { 27 | return func(ctx context.Context, request interface{}) (response interface{}, err error) { 28 | var span stdopentracing.Span 29 | span, ctx = stdopentracing.StartSpanFromContext(ctx, "authorize payment") 30 | span.SetTag("service", "payment") 31 | defer span.Finish() 32 | req := request.(AuthoriseRequest) 33 | authorisation, err := s.Authorise(req.Amount) 34 | return AuthoriseResponse{Authorisation: authorisation, Err: err}, nil 35 | } 36 | } 37 | 38 | // MakeHealthEndpoint returns current health of the given service. 39 | func MakeHealthEndpoint(s Service) endpoint.Endpoint { 40 | return func(ctx context.Context, request interface{}) (response interface{}, err error) { 41 | var span stdopentracing.Span 42 | span, ctx = stdopentracing.StartSpanFromContext(ctx, "health check") 43 | span.SetTag("service", "payment") 44 | defer span.Finish() 45 | health := s.Health() 46 | return healthResponse{Health: health}, nil 47 | } 48 | } 49 | 50 | // AuthoriseRequest represents a request for payment authorisation. 51 | // The Amount is the total amount of the transaction 52 | type AuthoriseRequest struct { 53 | Amount float32 `json:"amount"` 54 | } 55 | 56 | // AuthoriseResponse returns a response of type Authorisation and an error, Err. 57 | type AuthoriseResponse struct { 58 | Authorisation Authorisation 59 | Err error 60 | } 61 | 62 | type healthRequest struct { 63 | // 64 | } 65 | 66 | type healthResponse struct { 67 | Health []Health `json:"health"` 68 | } 69 | -------------------------------------------------------------------------------- /logging.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "github.com/go-kit/kit/log" 5 | "time" 6 | ) 7 | 8 | // LoggingMiddleware logs method calls, parameters, results, and elapsed time. 9 | func LoggingMiddleware(logger log.Logger) Middleware { 10 | return func(next Service) Service { 11 | return loggingMiddleware{ 12 | next: next, 13 | logger: logger, 14 | } 15 | } 16 | } 17 | 18 | type loggingMiddleware struct { 19 | next Service 20 | logger log.Logger 21 | } 22 | 23 | func (mw loggingMiddleware) Authorise(amount float32) (auth Authorisation, err error) { 24 | defer func(begin time.Time) { 25 | mw.logger.Log( 26 | "method", "Authorise", 27 | "result", auth.Authorised, 28 | "took", time.Since(begin), 29 | ) 30 | }(time.Now()) 31 | return mw.next.Authorise(amount) 32 | } 33 | 34 | func (mw loggingMiddleware) Health() (health []Health) { 35 | defer func(begin time.Time) { 36 | mw.logger.Log( 37 | "method", "Health", 38 | "result", len(health), 39 | "took", time.Since(begin), 40 | ) 41 | }(time.Now()) 42 | return mw.next.Health() 43 | } 44 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ev 4 | 5 | SCRIPT_DIR=$(dirname "$0") 6 | 7 | if [[ -z "$GROUP" ]] ; then 8 | echo "Cannot find GROUP env var" 9 | exit 1 10 | fi 11 | 12 | if [[ -z "$COMMIT" ]] ; then 13 | echo "Cannot find COMMIT env var" 14 | exit 1 15 | fi 16 | 17 | if [[ "$(uname)" == "Darwin" ]]; then 18 | DOCKER_CMD=docker 19 | else 20 | DOCKER_CMD="sudo docker" 21 | fi 22 | CODE_DIR=$(cd $SCRIPT_DIR/..; pwd) 23 | echo $CODE_DIR 24 | 25 | cp -r $CODE_DIR/cmd/ $CODE_DIR/docker/payment/cmd/ 26 | cp $CODE_DIR/*.go $CODE_DIR/docker/payment/ 27 | mkdir $CODE_DIR/docker/payment/vendor && cp $CODE_DIR/vendor/manifest $CODE_DIR/docker/payment/vendor/ 28 | 29 | REPO=${GROUP}/$(basename payment); 30 | 31 | $DOCKER_CMD build -t ${REPO}-dev -f $CODE_DIR/docker/payment/Dockerfile $CODE_DIR/docker/payment; 32 | $DOCKER_CMD create --name payment ${REPO}-dev; 33 | $DOCKER_CMD cp payment:/app $CODE_DIR/docker/payment/app; 34 | $DOCKER_CMD rm payment; 35 | $DOCKER_CMD build -t ${REPO}:${COMMIT} -f $CODE_DIR/docker/payment/Dockerfile-release $CODE_DIR/docker/payment; 36 | -------------------------------------------------------------------------------- /scripts/push.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ev 4 | 5 | if [[ -z "$GROUP" ]] ; then 6 | echo "Cannot find GROUP env var" 7 | exit 1 8 | fi 9 | 10 | if [[ -z "$COMMIT" ]] ; then 11 | echo "Cannot find COMMIT env var" 12 | exit 1 13 | fi 14 | 15 | push() { 16 | DOCKER_PUSH=1; 17 | while [ $DOCKER_PUSH -gt 0 ] ; do 18 | echo "Pushing $1"; 19 | docker push $1; 20 | DOCKER_PUSH=$(echo $?); 21 | if [[ "$DOCKER_PUSH" -gt 0 ]] ; then 22 | echo "Docker push failed with exit code $DOCKER_PUSH"; 23 | fi; 24 | done; 25 | } 26 | 27 | tag_and_push_all() { 28 | if [[ -z "$1" ]] ; then 29 | echo "Please pass the tag" 30 | exit 1 31 | else 32 | TAG=$1 33 | fi 34 | for m in ./docker/*/; do 35 | REPO=${GROUP}/$(basename $m) 36 | if [[ "$COMMIT" != "$TAG" ]]; then 37 | docker tag ${REPO}:${COMMIT} ${REPO}:${TAG} 38 | fi 39 | push "$REPO:$TAG"; 40 | done; 41 | } 42 | 43 | # Push snapshot when in master 44 | if [ "$TRAVIS_BRANCH" == "master" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then 45 | tag_and_push_all master-${COMMIT:0:8} 46 | fi; 47 | 48 | # Push tag and latest when tagged 49 | if [ -n "$TRAVIS_TAG" ]; then 50 | tag_and_push_all ${TRAVIS_TAG} 51 | tag_and_push_all latest 52 | fi; 53 | -------------------------------------------------------------------------------- /service.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | // Middleware decorates a service. 10 | type Middleware func(Service) Service 11 | 12 | type Service interface { 13 | Authorise(total float32) (Authorisation, error) // GET /paymentAuth 14 | Health() []Health // GET /health 15 | } 16 | 17 | type Authorisation struct { 18 | Authorised bool `json:"authorised"` 19 | Message string `json:"message"` 20 | } 21 | 22 | type Health struct { 23 | Service string `json:"service"` 24 | Status string `json:"status"` 25 | Time string `json:"time"` 26 | } 27 | 28 | // NewFixedService returns a simple implementation of the Service interface, 29 | // fixed over a predefined set of socks and tags. In a real service you'd 30 | // probably construct this with a database handle to your socks DB, etc. 31 | func NewAuthorisationService(declineOverAmount float32) Service { 32 | return &service{ 33 | declineOverAmount: declineOverAmount, 34 | } 35 | } 36 | 37 | type service struct { 38 | declineOverAmount float32 39 | } 40 | 41 | func (s *service) Authorise(amount float32) (Authorisation, error) { 42 | if amount == 0 { 43 | return Authorisation{}, ErrInvalidPaymentAmount 44 | } 45 | if amount < 0 { 46 | return Authorisation{}, ErrInvalidPaymentAmount 47 | } 48 | authorised := false 49 | message := "Payment declined" 50 | if amount <= s.declineOverAmount { 51 | authorised = true 52 | message = "Payment authorised" 53 | } else { 54 | message = fmt.Sprintf("Payment declined: amount exceeds %.2f", s.declineOverAmount) 55 | } 56 | return Authorisation{ 57 | Authorised: authorised, 58 | Message: message, 59 | }, nil 60 | } 61 | 62 | func (s *service) Health() []Health { 63 | var health []Health 64 | app := Health{"payment", "OK", time.Now().String()} 65 | health = append(health, app) 66 | return health 67 | } 68 | 69 | var ErrInvalidPaymentAmount = errors.New("Invalid payment amount") 70 | -------------------------------------------------------------------------------- /service_test.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import "testing" 4 | import "fmt" 5 | 6 | func TestAuthorise(t *testing.T) { 7 | result, _ := NewAuthorisationService(100).Authorise(10) 8 | expected := Authorisation{true, "Payment authorised"} 9 | if result != expected { 10 | t.Errorf("Authorise returned unexpected result: got %v want %v", 11 | result, expected) 12 | } 13 | } 14 | 15 | func TestFailOverCertainAmount(t *testing.T) { 16 | declineAmount := float32(10) 17 | result, _ := NewAuthorisationService(declineAmount).Authorise(100) 18 | expected := Authorisation{false, fmt.Sprintf("Payment declined: amount exceeds %.2f", declineAmount)} 19 | if result != expected { 20 | t.Errorf("Authorise returned unexpected result: got %v want %v", 21 | result, expected) 22 | } 23 | } 24 | 25 | func TestFailIfAmountIsZero(t *testing.T) { 26 | _, err := NewAuthorisationService(10).Authorise(0) 27 | _, ok := err.(error) 28 | if !ok { 29 | t.Errorf("Authorise returned unexpected result: got %v want %v", 30 | err, "Zero payment") 31 | } 32 | } 33 | 34 | func TestFailIfAmountNegative(t *testing.T) { 35 | _, err := NewAuthorisationService(10).Authorise(-1) 36 | _, ok := err.(error) 37 | if !ok { 38 | t.Errorf("Authorise returned unexpected result: got %v want %v", 39 | err, "Negative payment") 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6-alpine 2 | 3 | RUN apk add --no-cache \ 4 | ca-certificates \ 5 | curl \ 6 | openssl 7 | 8 | ENV DOCKER_BUCKET get.docker.com 9 | ENV DOCKER_VERSION 1.8.3 10 | 11 | RUN set -x \ 12 | && curl -fSL "https://${DOCKER_BUCKET}/builds/Linux/x86_64/docker-${DOCKER_VERSION}.tgz" -o docker.tgz \ 13 | && tar -xzvf docker.tgz \ 14 | && docker -v 15 | 16 | RUN pip install requests 17 | -------------------------------------------------------------------------------- /test/container.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import sys 3 | import unittest 4 | import os 5 | from util.Api import Api 6 | from time import sleep 7 | 8 | from util.Docker import Docker 9 | from util.Dredd import Dredd 10 | 11 | 12 | class PaymentContainerTest(unittest.TestCase): 13 | TAG = "latest" 14 | PORT = "8080" 15 | 16 | container_name = Docker().random_container_name('payment') 17 | 18 | def __init__(self, methodName='runTest'): 19 | super(PaymentContainerTest, self).__init__(methodName) 20 | self.ip = "" 21 | 22 | def setUp(self): 23 | command = ['docker', 'run', 24 | '-d', 25 | '--name', PaymentContainerTest.container_name, 26 | '-h', 'payment', 27 | 'weaveworksdemos/payment-dev:' + self.TAG, 28 | '/app', '-port=' + PaymentContainerTest.PORT] 29 | Docker().execute(command) 30 | self.ip = Docker().get_container_ip(PaymentContainerTest.container_name) 31 | 32 | def tearDown(self): 33 | Docker().kill_and_remove(PaymentContainerTest.container_name) 34 | 35 | def test_api_validated(self): 36 | limit = 30 37 | url = f'http://{self.ip}:{PaymentContainerTest.PORT}/' 38 | 39 | while Api().noResponse(url + 'payments/'): 40 | if limit == 0: 41 | self.fail("Couldn't get the API running") 42 | limit = limit - 1 43 | sleep(1) 44 | 45 | out = Dredd().test_against_endpoint("payment", 46 | url, 47 | links=[self.container_name], 48 | dump_streams=True) 49 | 50 | self.assertGreater(out.find("0 failing"), -1) 51 | self.assertGreater(out.find("0 errors"), -1) 52 | 53 | 54 | if __name__ == '__main__': 55 | parser = argparse.ArgumentParser() 56 | default_tag = "latest" 57 | parser.add_argument('--tag', default=default_tag, help='The tag of the image to use. (default: latest)') 58 | parser.add_argument('unittest_args', nargs='*') 59 | args = parser.parse_args() 60 | PaymentContainerTest.TAG = args.tag 61 | 62 | if PaymentContainerTest.TAG == "": 63 | PaymentContainerTest.TAG = default_tag 64 | 65 | # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone) 66 | sys.argv[1:] = args.unittest_args 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /test/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ev 4 | 5 | SCRIPT_DIR=`dirname "$0"` 6 | SCRIPT_NAME=`basename "$0"` 7 | SSH_OPTS=-oStrictHostKeyChecking=no 8 | 9 | if [[ "$(uname)" == "Darwin" ]]; then 10 | DOCKER_CMD=docker 11 | else 12 | DOCKER_CMD="sudo docker" 13 | fi 14 | 15 | if [[ -z $($DOCKER_CMD images | grep test-container) ]] ; then 16 | echo "Building test container" 17 | docker build -t test-container $SCRIPT_DIR > /dev/null 18 | fi 19 | 20 | echo "Testing $1" 21 | CODE_DIR=$(cd $SCRIPT_DIR/..; pwd) 22 | GOPATH=${GOPATH} 23 | 24 | $DOCKER_CMD run \ 25 | --rm \ 26 | --name test \ 27 | -v /var/run/docker.sock:/var/run/docker.sock \ 28 | -v $CODE_DIR:$CODE_DIR -w $CODE_DIR \ 29 | -e TRAVIS_JOB_ID=$TRAVIS_JOB_ID \ 30 | -e TRAVIS_BRANCH=$TRAVIS_BRANCH \ 31 | -e TRAVIS_PULL_REQUEST=$TRAVIS_PULL_REQUEST \ 32 | -e TRAVIS=$TRAVIS \ 33 | -e TAG=$TAG \ 34 | -e GOPATH=$GOPATH \ 35 | test-container \ 36 | sh -c "export PYTHONPATH=\$PYTHONPATH:\$PWD/test ; python test/$@" 37 | -------------------------------------------------------------------------------- /test/unit.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | from util.Docker import Docker 4 | 5 | class GoServices(unittest.TestCase): 6 | def test_go(self): 7 | script_dir = os.path.dirname(os.path.realpath(__file__)) 8 | code_dir = script_dir + "/.." 9 | goPath = os.environ['GOPATH'] 10 | command = ['docker', 'run', 11 | '--rm', 12 | '-v', goPath + ':/go/', 13 | '-v', code_dir + ':/go/src/github.com/microservices-demo/payment', 14 | '-w', '/go/src/github.com/microservices-demo/payment', 15 | '-e', 'GOPATH=/go/', 16 | 'golang:1.7', 17 | 'go', 'test', '-v', '-covermode=count', '-coverprofile=coverage.out' 18 | ] 19 | 20 | print(Docker().execute(command, dump_streams=True)) 21 | 22 | 23 | if __name__ == '__main__': 24 | unittest.main() 25 | -------------------------------------------------------------------------------- /test/util/Api.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | class Api: 4 | def noResponse(self, url): 5 | try: 6 | r = requests.get(url, timeout=5) 7 | except requests.exceptions.ConnectionError: 8 | return True 9 | return False 10 | -------------------------------------------------------------------------------- /test/util/Docker.py: -------------------------------------------------------------------------------- 1 | import re 2 | from subprocess import Popen, PIPE 3 | from random import random 4 | import time 5 | 6 | # From http://blog.bordage.pro/avoid-docker-py/ 7 | class Docker: 8 | def kill_and_remove(self, ctr_name): 9 | command = ['docker', 'rm', '-f', ctr_name] 10 | try: 11 | self.execute(command) 12 | return True 13 | except RuntimeError as e: 14 | print(e) 15 | return False 16 | 17 | def random_container_name(self, prefix): 18 | retstr = prefix + '-' 19 | for i in range(5): 20 | retstr += chr(int(round(random() * (122-97) + 97))) 21 | return retstr 22 | 23 | def get_container_ip(self, ctr_name): 24 | self.waitForContainerToStart(ctr_name) 25 | command = ['docker', 'inspect', 26 | '--format', '\'{{.NetworkSettings.IPAddress}}\'', 27 | ctr_name] 28 | return re.sub(r'[^0-9.]*', '', self.execute(command)) 29 | 30 | def execute(self, command, dump_streams=False): 31 | print("Running: " + ' '.join(command)) 32 | p = Popen(command, stdout=PIPE, stderr=PIPE) 33 | out, err = p.communicate() 34 | if dump_streams == True: 35 | print(out.decode('utf-8')) 36 | print(err.decode('utf-8')) 37 | return str(out.decode('utf-8')) 38 | 39 | def start_container(self, container_name="", image="", cmd="", host=""): 40 | command = ['docker', 'run', '-d', '-h', host, '--name', container_name, image] 41 | self.execute(command) 42 | 43 | def waitForContainerToStart(self, ctr_name): 44 | command = ['docker', 'inspect', 45 | '--format', '\'{{.State.Status}}\'', 46 | ctr_name] 47 | status = re.sub(r'[^a-z]*', '', self.execute(command)) 48 | while status != "running": 49 | time.sleep(1) 50 | print("Status: " + status + ". Waiting for container to start.") 51 | status = re.sub(r'[^a-z]*', '', self.execute(command)) 52 | -------------------------------------------------------------------------------- /test/util/Dredd.py: -------------------------------------------------------------------------------- 1 | from util.Docker import Docker 2 | from util.Api import Api 3 | import os 4 | import unittest 5 | 6 | class Dredd: 7 | image = 'weaveworksdemos/openapi' 8 | container_name = '' 9 | def test_against_endpoint(self, service, api_endpoint, links=[], env=[], dump_streams=False): 10 | self.container_name = Docker().random_container_name('openapi') 11 | command = ['docker', 'run', 12 | '-h', 'openapi', 13 | '--name', self.container_name, 14 | '-v', "{0}:{1}".format(os.getcwd() + "/api-spec/", "/tmp/specs/")] 15 | 16 | if links != []: 17 | [command.extend(["--link", x]) for x in links] 18 | 19 | if env != []: 20 | [command.extend(["--env", "{}={}".format(x[0], x[1])]) for x in env] 21 | 22 | command.extend([Dredd.image, 23 | "/tmp/specs/{0}.json".format(service), 24 | api_endpoint, 25 | "-f", 26 | "/tmp/specs/hooks.js".format(service)]) 27 | out = Docker().execute(command, dump_streams=dump_streams) 28 | 29 | Docker().kill_and_remove(self.container_name) 30 | return out 31 | -------------------------------------------------------------------------------- /test/util/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microservices-demo/payment/384e33447dda5334187517dda09566c9a17fd6af/test/util/__init__.py -------------------------------------------------------------------------------- /transport.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | 10 | "github.com/go-kit/kit/log" 11 | "github.com/go-kit/kit/circuitbreaker" 12 | "github.com/go-kit/kit/tracing/opentracing" 13 | httptransport "github.com/go-kit/kit/transport/http" 14 | "github.com/gorilla/mux" 15 | stdopentracing "github.com/opentracing/opentracing-go" 16 | "github.com/prometheus/client_golang/prometheus/promhttp" 17 | "github.com/streadway/handy/breaker" 18 | "golang.org/x/net/context" 19 | ) 20 | 21 | // MakeHTTPHandler mounts the endpoints into a REST-y HTTP handler. 22 | func MakeHTTPHandler(ctx context.Context, e Endpoints, logger log.Logger, tracer stdopentracing.Tracer) *mux.Router { 23 | r := mux.NewRouter().StrictSlash(false) 24 | options := []httptransport.ServerOption{ 25 | httptransport.ServerErrorLogger(logger), 26 | httptransport.ServerErrorEncoder(encodeError), 27 | } 28 | 29 | r.Methods("POST").Path("/paymentAuth").Handler(httptransport.NewServer( 30 | ctx, 31 | circuitbreaker.HandyBreaker(breaker.NewBreaker(0.2))(e.AuthoriseEndpoint), 32 | decodeAuthoriseRequest, 33 | encodeAuthoriseResponse, 34 | append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "POST /paymentAuth", logger)))..., 35 | )) 36 | r.Methods("GET").Path("/health").Handler(httptransport.NewServer( 37 | ctx, 38 | circuitbreaker.HandyBreaker(breaker.NewBreaker(0.2))(e.HealthEndpoint), 39 | decodeHealthRequest, 40 | encodeHealthResponse, 41 | append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "GET /health", logger)))..., 42 | )) 43 | r.Handle("/metrics", promhttp.Handler()) 44 | return r 45 | } 46 | 47 | func encodeError(_ context.Context, err error, w http.ResponseWriter) { 48 | code := http.StatusInternalServerError 49 | w.WriteHeader(code) 50 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 51 | json.NewEncoder(w).Encode(map[string]interface{}{ 52 | "error": err.Error(), 53 | "status_code": code, 54 | "status_text": http.StatusText(code), 55 | }) 56 | } 57 | 58 | func decodeAuthoriseRequest(_ context.Context, r *http.Request) (interface{}, error) { 59 | // Read the content 60 | var bodyBytes []byte 61 | if r.Body != nil { 62 | var err error 63 | bodyBytes, err = ioutil.ReadAll(r.Body) 64 | if err != nil { 65 | return nil, err 66 | } 67 | } 68 | // Save the content 69 | bodyString := string(bodyBytes) 70 | 71 | // Decode auth request 72 | var request AuthoriseRequest 73 | if err := json.Unmarshal(bodyBytes, &request); err != nil { 74 | return nil, err 75 | } 76 | 77 | // If amount isn't present, error 78 | if request.Amount == 0.0 { 79 | return nil, &UnmarshalKeyError{ 80 | Key: "amount", 81 | JSON: bodyString, 82 | } 83 | } 84 | return request, nil 85 | } 86 | 87 | type UnmarshalKeyError struct { 88 | Key string 89 | JSON string 90 | } 91 | 92 | func (e *UnmarshalKeyError) Error() string { 93 | return fmt.Sprintf("Cannot unmarshal object key %q from JSON: %s", e.Key, e.JSON) 94 | } 95 | 96 | var ErrInvalidJson = errors.New("Invalid json") 97 | 98 | func encodeAuthoriseResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 99 | resp := response.(AuthoriseResponse) 100 | if resp.Err != nil { 101 | encodeError(ctx, resp.Err, w) 102 | return nil 103 | } 104 | return encodeResponse(ctx, w, resp.Authorisation) 105 | } 106 | 107 | func decodeHealthRequest(_ context.Context, r *http.Request) (interface{}, error) { 108 | return struct{}{}, nil 109 | } 110 | 111 | func encodeHealthResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 112 | return encodeResponse(ctx, w, response.(healthResponse)) 113 | } 114 | 115 | func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { 116 | // All of our response objects are JSON serializable, so we just do that. 117 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 118 | return json.NewEncoder(w).Encode(response) 119 | } 120 | -------------------------------------------------------------------------------- /vendor/manifest: -------------------------------------------------------------------------------- 1 | { 2 | "version": 0, 3 | "dependencies": [ 4 | { 5 | "importpath": "cloud.google.com/go/compute/metadata", 6 | "repository": "https://code.googlesource.com/gocloud", 7 | "vcs": "git", 8 | "revision": "daf945bb8684eb8df711af0c3e3a07930a2a01b0", 9 | "branch": "master", 10 | "path": "/compute/metadata", 11 | "notests": true 12 | }, 13 | { 14 | "importpath": "cloud.google.com/go/internal", 15 | "repository": "https://code.googlesource.com/gocloud", 16 | "vcs": "git", 17 | "revision": "daf945bb8684eb8df711af0c3e3a07930a2a01b0", 18 | "branch": "master", 19 | "path": "internal", 20 | "notests": true 21 | }, 22 | { 23 | "importpath": "github.com/Shopify/sarama", 24 | "repository": "https://github.com/Shopify/sarama", 25 | "vcs": "git", 26 | "revision": "0fb560e5f7fbcaee2f75e3c34174320709f69944", 27 | "branch": "master", 28 | "notests": true 29 | }, 30 | { 31 | "importpath": "github.com/Sirupsen/logrus", 32 | "repository": "https://github.com/Sirupsen/logrus", 33 | "vcs": "git", 34 | "revision": "10f801ebc38b33738c9d17d50860f484a0988ff5", 35 | "branch": "master", 36 | "notests": true 37 | }, 38 | { 39 | "importpath": "github.com/VividCortex/gohistogram", 40 | "repository": "https://github.com/VividCortex/gohistogram", 41 | "vcs": "git", 42 | "revision": "51564d9861991fb0ad0f531c99ef602d0f9866e6", 43 | "branch": "master", 44 | "notests": true 45 | }, 46 | { 47 | "importpath": "github.com/afex/hystrix-go/hystrix", 48 | "repository": "https://github.com/afex/hystrix-go", 49 | "vcs": "git", 50 | "revision": "39520ddd07a9d9a071d615f7476798659f5a3b89", 51 | "branch": "master", 52 | "path": "/hystrix", 53 | "notests": true 54 | }, 55 | { 56 | "importpath": "github.com/apache/thrift/lib/go/thrift", 57 | "repository": "https://github.com/apache/thrift", 58 | "vcs": "git", 59 | "revision": "d8bb0e3b9ff7e6cecfc85c01a81280dc3d046430", 60 | "branch": "master", 61 | "path": "/lib/go/thrift", 62 | "notests": true 63 | }, 64 | { 65 | "importpath": "github.com/beorn7/perks/quantile", 66 | "repository": "https://github.com/beorn7/perks", 67 | "vcs": "git", 68 | "revision": "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9", 69 | "branch": "master", 70 | "path": "/quantile", 71 | "notests": true 72 | }, 73 | { 74 | "importpath": "github.com/circonus-labs/circonus-gometrics", 75 | "repository": "https://github.com/circonus-labs/circonus-gometrics", 76 | "vcs": "git", 77 | "revision": "03493d041ec6ba6c77679bbae9f6129e246c08c7", 78 | "branch": "master", 79 | "notests": true 80 | }, 81 | { 82 | "importpath": "github.com/circonus-labs/circonusllhist", 83 | "repository": "https://github.com/circonus-labs/circonusllhist", 84 | "vcs": "git", 85 | "revision": "7d649b46cdc2cd2ed102d350688a75a4fd7778c6", 86 | "branch": "master", 87 | "notests": true 88 | }, 89 | { 90 | "importpath": "github.com/davecgh/go-spew/spew", 91 | "repository": "https://github.com/davecgh/go-spew", 92 | "vcs": "git", 93 | "revision": "346938d642f2ec3594ed81d874461961cd0faa76", 94 | "branch": "master", 95 | "path": "/spew", 96 | "notests": true 97 | }, 98 | { 99 | "importpath": "github.com/eapache/go-resiliency/breaker", 100 | "repository": "https://github.com/eapache/go-resiliency", 101 | "vcs": "git", 102 | "revision": "b86b1ec0dd4209a588dc1285cdd471e73525c0b3", 103 | "branch": "master", 104 | "path": "/breaker", 105 | "notests": true 106 | }, 107 | { 108 | "importpath": "github.com/eapache/go-xerial-snappy", 109 | "repository": "https://github.com/eapache/go-xerial-snappy", 110 | "vcs": "git", 111 | "revision": "bb955e01b9346ac19dc29eb16586c90ded99a98c", 112 | "branch": "master", 113 | "notests": true 114 | }, 115 | { 116 | "importpath": "github.com/eapache/queue", 117 | "repository": "https://github.com/eapache/queue", 118 | "vcs": "git", 119 | "revision": "44cc805cf13205b55f69e14bcb69867d1ae92f98", 120 | "branch": "master", 121 | "notests": true 122 | }, 123 | { 124 | "importpath": "github.com/felixge/httpsnoop", 125 | "repository": "https://github.com/felixge/httpsnoop", 126 | "vcs": "git", 127 | "revision": "287b56e9e314227d3113c7c6b434d31aec68089d", 128 | "branch": "master", 129 | "notests": true 130 | }, 131 | { 132 | "importpath": "github.com/go-kit/kit/circuitbreaker", 133 | "repository": "https://github.com/go-kit/kit", 134 | "vcs": "git", 135 | "revision": "bbb2306ec1318f1da5e9cba56bf933d0c7641e84", 136 | "branch": "master", 137 | "path": "/circuitbreaker", 138 | "notests": true 139 | }, 140 | { 141 | "importpath": "github.com/go-kit/kit/endpoint", 142 | "repository": "https://github.com/go-kit/kit", 143 | "vcs": "git", 144 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 145 | "branch": "master", 146 | "path": "/endpoint", 147 | "notests": true 148 | }, 149 | { 150 | "importpath": "github.com/go-kit/kit/log", 151 | "repository": "https://github.com/go-kit/kit", 152 | "vcs": "git", 153 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 154 | "branch": "master", 155 | "path": "log", 156 | "notests": true 157 | }, 158 | { 159 | "importpath": "github.com/go-kit/kit/metrics", 160 | "repository": "https://github.com/go-kit/kit", 161 | "vcs": "git", 162 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 163 | "branch": "master", 164 | "path": "metrics", 165 | "notests": true 166 | }, 167 | { 168 | "importpath": "github.com/go-kit/kit/tracing/opentracing", 169 | "repository": "https://github.com/go-kit/kit", 170 | "vcs": "git", 171 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 172 | "branch": "master", 173 | "path": "/tracing/opentracing", 174 | "notests": true 175 | }, 176 | { 177 | "importpath": "github.com/go-kit/kit/transport/http", 178 | "repository": "https://github.com/go-kit/kit", 179 | "vcs": "git", 180 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 181 | "branch": "master", 182 | "path": "/transport/http", 183 | "notests": true 184 | }, 185 | { 186 | "importpath": "github.com/go-kit/kit/util/conn", 187 | "repository": "https://github.com/go-kit/kit", 188 | "vcs": "git", 189 | "revision": "905b60253dbac4a14625ce52217ede00d3a3aca7", 190 | "branch": "master", 191 | "path": "util/conn", 192 | "notests": true 193 | }, 194 | { 195 | "importpath": "github.com/go-logfmt/logfmt", 196 | "repository": "https://github.com/go-logfmt/logfmt", 197 | "vcs": "git", 198 | "revision": "390ab7935ee28ec6b286364bba9b4dd6410cb3d5", 199 | "branch": "master", 200 | "notests": true 201 | }, 202 | { 203 | "importpath": "github.com/go-stack/stack", 204 | "repository": "https://github.com/go-stack/stack", 205 | "vcs": "git", 206 | "revision": "100eb0c0a9c5b306ca2fb4f165df21d80ada4b82", 207 | "branch": "master", 208 | "notests": true 209 | }, 210 | { 211 | "importpath": "github.com/gogo/protobuf/proto", 212 | "repository": "https://github.com/gogo/protobuf", 213 | "vcs": "git", 214 | "revision": "84af2615df1ba1d35cc975ba94b64ee67d6c196e", 215 | "branch": "master", 216 | "path": "/proto", 217 | "notests": true 218 | }, 219 | { 220 | "importpath": "github.com/gogo/protobuf/sortkeys", 221 | "repository": "https://github.com/gogo/protobuf", 222 | "vcs": "git", 223 | "revision": "84af2615df1ba1d35cc975ba94b64ee67d6c196e", 224 | "branch": "master", 225 | "path": "sortkeys", 226 | "notests": true 227 | }, 228 | { 229 | "importpath": "github.com/gogo/protobuf/types", 230 | "repository": "https://github.com/gogo/protobuf", 231 | "vcs": "git", 232 | "revision": "84af2615df1ba1d35cc975ba94b64ee67d6c196e", 233 | "branch": "master", 234 | "path": "types", 235 | "notests": true 236 | }, 237 | { 238 | "importpath": "github.com/golang/glog", 239 | "repository": "https://github.com/golang/glog", 240 | "vcs": "git", 241 | "revision": "23def4e6c14b4da8ac2ed8007337bc5eb5007998", 242 | "branch": "master", 243 | "notests": true 244 | }, 245 | { 246 | "importpath": "github.com/golang/mock/gomock", 247 | "repository": "https://github.com/golang/mock", 248 | "vcs": "git", 249 | "revision": "bd3c8e81be01eef76d4b503f5e687d2d1354d2d9", 250 | "branch": "master", 251 | "path": "/gomock", 252 | "notests": true 253 | }, 254 | { 255 | "importpath": "github.com/golang/protobuf/proto", 256 | "repository": "https://github.com/golang/protobuf", 257 | "vcs": "git", 258 | "revision": "8ee79997227bf9b34611aee7946ae64735e6fd93", 259 | "branch": "master", 260 | "path": "/proto", 261 | "notests": true 262 | }, 263 | { 264 | "importpath": "github.com/golang/protobuf/protoc-gen-go/descriptor", 265 | "repository": "https://github.com/golang/protobuf", 266 | "vcs": "git", 267 | "revision": "c9c7427a2a70d2eb3bafa0ab2dc163e45f143317", 268 | "branch": "master", 269 | "path": "/protoc-gen-go/descriptor", 270 | "notests": true 271 | }, 272 | { 273 | "importpath": "github.com/golang/protobuf/ptypes/any", 274 | "repository": "https://github.com/golang/protobuf", 275 | "vcs": "git", 276 | "revision": "8ee79997227bf9b34611aee7946ae64735e6fd93", 277 | "branch": "master", 278 | "path": "ptypes/any", 279 | "notests": true 280 | }, 281 | { 282 | "importpath": "github.com/golang/snappy", 283 | "repository": "https://github.com/golang/snappy", 284 | "vcs": "git", 285 | "revision": "d9eb7a3d35ec988b8585d4a0068e462c27d28380", 286 | "branch": "master", 287 | "notests": true 288 | }, 289 | { 290 | "importpath": "github.com/googleapis/gax-go", 291 | "repository": "https://github.com/googleapis/gax-go", 292 | "vcs": "git", 293 | "revision": "9af46dd5a1713e8b5cd71106287eba3cefdde50b", 294 | "branch": "master", 295 | "notests": true 296 | }, 297 | { 298 | "importpath": "github.com/gorilla/context", 299 | "repository": "https://github.com/gorilla/context", 300 | "vcs": "git", 301 | "revision": "08b5f424b9271eedf6f9f0ce86cb9396ed337a42", 302 | "branch": "master", 303 | "notests": true 304 | }, 305 | { 306 | "importpath": "github.com/gorilla/mux", 307 | "repository": "https://github.com/gorilla/mux", 308 | "vcs": "git", 309 | "revision": "757bef944d0f21880861c2dd9c871ca543023cba", 310 | "branch": "master", 311 | "notests": true 312 | }, 313 | { 314 | "importpath": "github.com/hashicorp/go-cleanhttp", 315 | "repository": "https://github.com/hashicorp/go-cleanhttp", 316 | "vcs": "git", 317 | "revision": "ad28ea4487f05916463e2423a55166280e8254b5", 318 | "branch": "master", 319 | "notests": true 320 | }, 321 | { 322 | "importpath": "github.com/hashicorp/go-retryablehttp", 323 | "repository": "https://github.com/hashicorp/go-retryablehttp", 324 | "vcs": "git", 325 | "revision": "6e85be8fee1dcaa02c0eaaac2df5a8fbecf94145", 326 | "branch": "master", 327 | "notests": true 328 | }, 329 | { 330 | "importpath": "github.com/influxdata/influxdb/client/v2", 331 | "repository": "https://github.com/influxdata/influxdb", 332 | "vcs": "git", 333 | "revision": "c783c3d05fee10575aa612a3ff87d71b4cba02f4", 334 | "branch": "master", 335 | "path": "/client/v2", 336 | "notests": true 337 | }, 338 | { 339 | "importpath": "github.com/influxdata/influxdb/models", 340 | "repository": "https://github.com/influxdata/influxdb", 341 | "vcs": "git", 342 | "revision": "c783c3d05fee10575aa612a3ff87d71b4cba02f4", 343 | "branch": "master", 344 | "path": "models", 345 | "notests": true 346 | }, 347 | { 348 | "importpath": "github.com/influxdata/influxdb/pkg/escape", 349 | "repository": "https://github.com/influxdata/influxdb", 350 | "vcs": "git", 351 | "revision": "c783c3d05fee10575aa612a3ff87d71b4cba02f4", 352 | "branch": "master", 353 | "path": "pkg/escape", 354 | "notests": true 355 | }, 356 | { 357 | "importpath": "github.com/klauspost/crc32", 358 | "repository": "https://github.com/klauspost/crc32", 359 | "vcs": "git", 360 | "revision": "cb6bfca970f6908083f26f39a79009d608efd5cd", 361 | "branch": "master", 362 | "notests": true 363 | }, 364 | { 365 | "importpath": "github.com/kr/logfmt", 366 | "repository": "https://github.com/kr/logfmt", 367 | "vcs": "git", 368 | "revision": "b84e30acd515aadc4b783ad4ff83aff3299bdfe0", 369 | "branch": "master", 370 | "notests": true 371 | }, 372 | { 373 | "importpath": "github.com/matttproud/golang_protobuf_extensions/pbutil", 374 | "repository": "https://github.com/matttproud/golang_protobuf_extensions", 375 | "vcs": "git", 376 | "revision": "c12348ce28de40eed0136aa2b644d0ee0650e56c", 377 | "branch": "master", 378 | "path": "/pbutil", 379 | "notests": true 380 | }, 381 | { 382 | "importpath": "github.com/opentracing/opentracing-go", 383 | "repository": "https://github.com/opentracing/opentracing-go", 384 | "vcs": "git", 385 | "revision": "5e5abf838007b08f96ae057bc182636a178da0b9", 386 | "branch": "master", 387 | "notests": true, 388 | "allfiles": true 389 | }, 390 | { 391 | "importpath": "github.com/openzipkin/zipkin-go-opentracing", 392 | "repository": "https://github.com/openzipkin/zipkin-go-opentracing", 393 | "vcs": "git", 394 | "revision": "594640b9ef7e5c994e8d9499359d693c032d738c", 395 | "branch": "master", 396 | "notests": true, 397 | "allfiles": true 398 | }, 399 | { 400 | "importpath": "github.com/performancecopilot/speed", 401 | "repository": "https://github.com/performancecopilot/speed", 402 | "vcs": "git", 403 | "revision": "6c862057c50f0d597c08fd8c58cf88376bb243f3", 404 | "branch": "master", 405 | "notests": true 406 | }, 407 | { 408 | "importpath": "github.com/pierrec/lz4", 409 | "repository": "https://github.com/pierrec/lz4", 410 | "vcs": "git", 411 | "revision": "5c9560bfa9ace2bf86080bf40d46b34ae44604df", 412 | "branch": "master", 413 | "notests": true 414 | }, 415 | { 416 | "importpath": "github.com/pierrec/xxHash/xxHash32", 417 | "repository": "https://github.com/pierrec/xxHash", 418 | "vcs": "git", 419 | "revision": "5a004441f897722c627870a981d02b29924215fa", 420 | "branch": "master", 421 | "path": "/xxHash32", 422 | "notests": true 423 | }, 424 | { 425 | "importpath": "github.com/prometheus/client_golang/prometheus", 426 | "repository": "https://github.com/prometheus/client_golang", 427 | "vcs": "git", 428 | "revision": "575f371f7862609249a1be4c9145f429fe065e32", 429 | "branch": "master", 430 | "path": "/prometheus", 431 | "notests": true 432 | }, 433 | { 434 | "importpath": "github.com/prometheus/client_model/go", 435 | "repository": "https://github.com/prometheus/client_model", 436 | "vcs": "git", 437 | "revision": "fa8ad6fec33561be4280a8f0514318c79d7f6cb6", 438 | "branch": "master", 439 | "path": "/go", 440 | "notests": true 441 | }, 442 | { 443 | "importpath": "github.com/prometheus/common/expfmt", 444 | "repository": "https://github.com/prometheus/common", 445 | "vcs": "git", 446 | "revision": "6d76b79f239843a04e8ad8dfd8fcadfa3920236f", 447 | "branch": "master", 448 | "path": "/expfmt", 449 | "notests": true 450 | }, 451 | { 452 | "importpath": "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg", 453 | "repository": "https://github.com/prometheus/common", 454 | "vcs": "git", 455 | "revision": "6d76b79f239843a04e8ad8dfd8fcadfa3920236f", 456 | "branch": "master", 457 | "path": "internal/bitbucket.org/ww/goautoneg", 458 | "notests": true 459 | }, 460 | { 461 | "importpath": "github.com/prometheus/common/model", 462 | "repository": "https://github.com/prometheus/common", 463 | "vcs": "git", 464 | "revision": "6d76b79f239843a04e8ad8dfd8fcadfa3920236f", 465 | "branch": "master", 466 | "path": "model", 467 | "notests": true 468 | }, 469 | { 470 | "importpath": "github.com/prometheus/procfs", 471 | "repository": "https://github.com/prometheus/procfs", 472 | "vcs": "git", 473 | "revision": "fcdb11ccb4389efb1b210b7ffb623ab71c5fdd60", 474 | "branch": "master", 475 | "notests": true 476 | }, 477 | { 478 | "importpath": "github.com/rcrowley/go-metrics", 479 | "repository": "https://github.com/rcrowley/go-metrics", 480 | "vcs": "git", 481 | "revision": "1f30fe9094a513ce4c700b9a54458bbb0c96996c", 482 | "branch": "master", 483 | "notests": true 484 | }, 485 | { 486 | "importpath": "github.com/sony/gobreaker", 487 | "repository": "https://github.com/sony/gobreaker", 488 | "vcs": "git", 489 | "revision": "809bcd5a528f344e95c2368796c9225d128f9b3e", 490 | "branch": "master", 491 | "notests": true 492 | }, 493 | { 494 | "importpath": "github.com/stathat/go", 495 | "repository": "https://github.com/stathat/go", 496 | "vcs": "git", 497 | "revision": "74669b9f388d9d788c97399a0824adbfee78400e", 498 | "branch": "master", 499 | "notests": true 500 | }, 501 | { 502 | "importpath": "github.com/streadway/handy/breaker", 503 | "repository": "https://github.com/streadway/handy", 504 | "vcs": "git", 505 | "revision": "f450267a206e480d863d2a92846a40f6e2896b2a", 506 | "branch": "master", 507 | "path": "/breaker", 508 | "notests": true 509 | }, 510 | { 511 | "importpath": "github.com/stretchr/testify/assert", 512 | "repository": "https://github.com/stretchr/testify", 513 | "vcs": "git", 514 | "revision": "2402e8e7a02fc811447d11f881aa9746cdc57983", 515 | "branch": "master", 516 | "path": "/assert", 517 | "notests": true, 518 | "allfiles": true 519 | }, 520 | { 521 | "importpath": "github.com/stretchr/testify/require", 522 | "repository": "https://github.com/stretchr/testify", 523 | "vcs": "git", 524 | "revision": "2402e8e7a02fc811447d11f881aa9746cdc57983", 525 | "branch": "master", 526 | "path": "require", 527 | "notests": true, 528 | "allfiles": true 529 | }, 530 | { 531 | "importpath": "github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew", 532 | "repository": "https://github.com/stretchr/testify", 533 | "vcs": "git", 534 | "revision": "2402e8e7a02fc811447d11f881aa9746cdc57983", 535 | "branch": "master", 536 | "path": "vendor/github.com/davecgh/go-spew/spew", 537 | "notests": true, 538 | "allfiles": true 539 | }, 540 | { 541 | "importpath": "github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib", 542 | "repository": "https://github.com/stretchr/testify", 543 | "vcs": "git", 544 | "revision": "2402e8e7a02fc811447d11f881aa9746cdc57983", 545 | "branch": "master", 546 | "path": "vendor/github.com/pmezard/go-difflib/difflib", 547 | "notests": true, 548 | "allfiles": true 549 | }, 550 | { 551 | "importpath": "github.com/weaveworks/common/errors", 552 | "repository": "https://github.com/weaveworks/common", 553 | "vcs": "git", 554 | "revision": "f94043b3da140c7a735b1f2f286d72d19014b200", 555 | "branch": "master", 556 | "path": "errors", 557 | "notests": true 558 | }, 559 | { 560 | "importpath": "github.com/weaveworks/common/middleware", 561 | "repository": "https://github.com/weaveworks/common", 562 | "vcs": "git", 563 | "revision": "f94043b3da140c7a735b1f2f286d72d19014b200", 564 | "branch": "master", 565 | "path": "/middleware", 566 | "notests": true 567 | }, 568 | { 569 | "importpath": "github.com/weaveworks/common/user", 570 | "repository": "https://github.com/weaveworks/common", 571 | "vcs": "git", 572 | "revision": "f94043b3da140c7a735b1f2f286d72d19014b200", 573 | "branch": "master", 574 | "path": "user", 575 | "notests": true 576 | }, 577 | { 578 | "importpath": "go4.org/syncutil/singleflight", 579 | "repository": "https://github.com/camlistore/go4", 580 | "vcs": "git", 581 | "revision": "169ea6cabe2a4888dba958edaecc9e9751adc711", 582 | "branch": "master", 583 | "path": "/syncutil/singleflight", 584 | "notests": true 585 | }, 586 | { 587 | "importpath": "golang.org/x/crypto/acme", 588 | "repository": "https://go.googlesource.com/crypto", 589 | "vcs": "git", 590 | "revision": "459e26527287adbc2adcc5d0d49abff9a5f315a7", 591 | "branch": "master", 592 | "path": "acme", 593 | "notests": true 594 | }, 595 | { 596 | "importpath": "golang.org/x/crypto/ssh/terminal", 597 | "repository": "https://go.googlesource.com/crypto", 598 | "vcs": "git", 599 | "revision": "459e26527287adbc2adcc5d0d49abff9a5f315a7", 600 | "branch": "master", 601 | "path": "ssh/terminal", 602 | "notests": true 603 | }, 604 | { 605 | "importpath": "golang.org/x/net/context", 606 | "repository": "https://go.googlesource.com/net", 607 | "vcs": "git", 608 | "revision": "8fd7f25955530b92e73e9e1932a41b522b22ccd9", 609 | "branch": "master", 610 | "path": "/context", 611 | "notests": true 612 | }, 613 | { 614 | "importpath": "golang.org/x/net/http2", 615 | "repository": "https://go.googlesource.com/net", 616 | "vcs": "git", 617 | "revision": "a6577fac2d73be281a500b310739095313165611", 618 | "branch": "master", 619 | "path": "/http2", 620 | "notests": true 621 | }, 622 | { 623 | "importpath": "golang.org/x/net/idna", 624 | "repository": "https://go.googlesource.com/net", 625 | "vcs": "git", 626 | "revision": "a6577fac2d73be281a500b310739095313165611", 627 | "branch": "master", 628 | "path": "idna", 629 | "notests": true 630 | }, 631 | { 632 | "importpath": "golang.org/x/net/internal/timeseries", 633 | "repository": "https://go.googlesource.com/net", 634 | "vcs": "git", 635 | "revision": "8fd7f25955530b92e73e9e1932a41b522b22ccd9", 636 | "branch": "master", 637 | "path": "internal/timeseries", 638 | "notests": true 639 | }, 640 | { 641 | "importpath": "golang.org/x/net/lex/httplex", 642 | "repository": "https://go.googlesource.com/net", 643 | "vcs": "git", 644 | "revision": "a6577fac2d73be281a500b310739095313165611", 645 | "branch": "master", 646 | "path": "lex/httplex", 647 | "notests": true 648 | }, 649 | { 650 | "importpath": "golang.org/x/net/trace", 651 | "repository": "https://go.googlesource.com/net", 652 | "vcs": "git", 653 | "revision": "8fd7f25955530b92e73e9e1932a41b522b22ccd9", 654 | "branch": "master", 655 | "path": "/trace", 656 | "notests": true 657 | }, 658 | { 659 | "importpath": "golang.org/x/oauth2", 660 | "repository": "https://go.googlesource.com/oauth2", 661 | "vcs": "git", 662 | "revision": "7fdf09982454086d5570c7db3e11f360194830ca", 663 | "branch": "master", 664 | "notests": true 665 | }, 666 | { 667 | "importpath": "golang.org/x/sys/unix", 668 | "repository": "https://go.googlesource.com/sys", 669 | "vcs": "git", 670 | "revision": "99f16d856c9836c42d24e7ab64ea72916925fa97", 671 | "branch": "master", 672 | "path": "/unix", 673 | "notests": true 674 | }, 675 | { 676 | "importpath": "google.golang.org/api/compute/v1", 677 | "repository": "https://code.googlesource.com/google-api-go-client", 678 | "vcs": "git", 679 | "revision": "16ab375f94503bfa0d19db78e96bffbe1a34354f", 680 | "branch": "master", 681 | "path": "/compute/v1", 682 | "notests": true 683 | }, 684 | { 685 | "importpath": "google.golang.org/api/gensupport", 686 | "repository": "https://code.googlesource.com/google-api-go-client", 687 | "vcs": "git", 688 | "revision": "16ab375f94503bfa0d19db78e96bffbe1a34354f", 689 | "branch": "master", 690 | "path": "gensupport", 691 | "notests": true 692 | }, 693 | { 694 | "importpath": "google.golang.org/api/googleapi", 695 | "repository": "https://code.googlesource.com/google-api-go-client", 696 | "vcs": "git", 697 | "revision": "16ab375f94503bfa0d19db78e96bffbe1a34354f", 698 | "branch": "master", 699 | "path": "googleapi", 700 | "notests": true 701 | }, 702 | { 703 | "importpath": "google.golang.org/appengine", 704 | "repository": "https://github.com/golang/appengine", 705 | "vcs": "git", 706 | "revision": "b79c28f0197795b4050bfcd7c4c2209136c594b1", 707 | "branch": "master", 708 | "notests": true 709 | }, 710 | { 711 | "importpath": "google.golang.org/grpc", 712 | "repository": "https://github.com/grpc/grpc-go", 713 | "vcs": "git", 714 | "revision": "cdee119ee21e61eef7093a41ba148fa83585e143", 715 | "branch": "master", 716 | "notests": true 717 | }, 718 | { 719 | "importpath": "gopkg.in/airbrake/gobrake.v2", 720 | "repository": "https://gopkg.in/airbrake/gobrake.v2", 721 | "vcs": "git", 722 | "revision": "668876711219e8b0206e2994bf0a59d889c775aa", 723 | "branch": "master", 724 | "notests": true 725 | }, 726 | { 727 | "importpath": "gopkg.in/gemnasium/logrus-airbrake-hook.v2", 728 | "repository": "https://gopkg.in/gemnasium/logrus-airbrake-hook.v2", 729 | "vcs": "git", 730 | "revision": "bfee1239d796830ca346767650cce5ba90d58c57", 731 | "branch": "master", 732 | "notests": true 733 | } 734 | ] 735 | } -------------------------------------------------------------------------------- /wiring.go: -------------------------------------------------------------------------------- 1 | package payment 2 | 3 | import ( 4 | "net/http" 5 | "os" 6 | 7 | "github.com/go-kit/kit/log" 8 | "golang.org/x/net/context" 9 | 10 | stdopentracing "github.com/opentracing/opentracing-go" 11 | "github.com/prometheus/client_golang/prometheus" 12 | "github.com/weaveworks/common/middleware" 13 | ) 14 | 15 | var ( 16 | HTTPLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{ 17 | Name: "http_request_duration_seconds", 18 | Help: "Time (in seconds) spent serving HTTP requests.", 19 | Buckets: prometheus.DefBuckets, 20 | }, []string{"method", "path", "status_code", "isWS"}) 21 | ) 22 | 23 | func init() { 24 | prometheus.MustRegister(HTTPLatency) 25 | } 26 | 27 | func WireUp(ctx context.Context, declineAmount float32, tracer stdopentracing.Tracer, serviceName string) (http.Handler, log.Logger) { 28 | // Log domain. 29 | var logger log.Logger 30 | { 31 | logger = log.NewLogfmtLogger(os.Stderr) 32 | logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC) 33 | logger = log.NewContext(logger).With("caller", log.DefaultCaller) 34 | } 35 | 36 | // Service domain. 37 | var service Service 38 | { 39 | service = NewAuthorisationService(declineAmount) 40 | service = LoggingMiddleware(logger)(service) 41 | } 42 | 43 | // Endpoint domain. 44 | endpoints := MakeEndpoints(service, tracer) 45 | 46 | router := MakeHTTPHandler(ctx, endpoints, logger, tracer) 47 | 48 | httpMiddleware := []middleware.Interface{ 49 | middleware.Instrument{ 50 | Duration: HTTPLatency, 51 | RouteMatcher: router, 52 | }, 53 | } 54 | 55 | // Handler 56 | handler := middleware.Merge(httpMiddleware...).Wrap(router) 57 | 58 | return handler, logger 59 | } 60 | --------------------------------------------------------------------------------