├── .devcontainer.json ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── settings.json ├── Dockerfile ├── LICENSE ├── README.md ├── common └── errors.go ├── docs ├── DEV-WITH-VSCODE.md ├── DEV-WITHOUT-VSCODE.md └── images │ └── vscode-ask-reopen-in-container.png ├── go.mod ├── go.sum ├── main.go ├── scripts └── start-devcontainer.sh └── users ├── constants.go ├── entities.go ├── entities_test.go ├── interfaces.go └── repositories.go /.devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "dockerFile": "Dockerfile", 3 | // Configure port mapping between localhost and development container, 4 | // should be updated respectively to exposed service ports of referencing container. 5 | "appPort": [ 6 | "8000:8000" 7 | ], 8 | // Configure to mount local workspace directory to an appropriate workspace directory 9 | // within development container. 10 | "workspaceMount": "src=${localWorkspaceFolder},dst=/root/project,type=bind", 11 | "workspaceFolder": "/root/project", 12 | // Configure VSCode extensions to be installed into development container's underlying VSCode-Server 13 | // once having finished launching. 14 | "extensions": [ 15 | "ms-vscode.go" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Go template 2 | # Binaries for programs and plugins 3 | *.exe 4 | *.exe~ 5 | *.dll 6 | *.so 7 | *.dylib 8 | 9 | # Test binary, built with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Dependency directories 16 | vendor/ 17 | 18 | ### VisualStudioCode template 19 | .vscode/* 20 | !.vscode/settings.json 21 | !.vscode/tasks.json 22 | !.vscode/launch.json 23 | !.vscode/extensions.json 24 | __debug_bin 25 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-docker", 4 | "ms-vscode-remote.remote-containers" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Launch", 6 | "type": "go", 7 | "request": "launch", 8 | "mode": "auto", 9 | "program": "${workspaceFolder}/main.go", 10 | "env": {}, 11 | "args": [] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/.git": true, 4 | "**/.svn": true, 5 | "**/.hg": true, 6 | "**/CVS": true, 7 | "**/.DS_Store": true, 8 | "__debug_bin": true, 9 | "vendor/": true, 10 | "go.sum": true 11 | }, 12 | "files.trimTrailingWhitespace": true, 13 | "files.trimFinalNewlines": true, 14 | "files.insertFinalNewline": true, 15 | "remote.extensionKind": { 16 | "ms-azuretools.vscode-docker": "ui", 17 | "ms-vscode-remote.remote-containers": "ui" 18 | }, 19 | "editor.formatOnSave": true, 20 | "editor.formatOnPaste": true 21 | } 22 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1 2 | 3 | # Configure to avoid redundant error "debconf: delaying package configuration, since apt-utils is not installed". 4 | # See https://code.visualstudio.com/docs/remote/containers-advanced#_debconf-delaying-package-configuration-since-aptutils-is-not-installed. 5 | ENV DEBIAN_FRONTEND=noninteractive 6 | RUN apt-get update && apt-get -y install --no-install-recommends apt-utils 7 | 8 | # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed. 9 | RUN apt-get -y install git iproute2 procps lsb-release 10 | 11 | # Enable Go Modules. 12 | ENV GO111MODULE=on 13 | 14 | # Install essential tools for Go development. 15 | RUN go get \ 16 | golang.org/x/tools/gopls@latest \ 17 | github.com/mdempsky/gocode \ 18 | github.com/uudashr/gopkgs/cmd/gopkgs \ 19 | github.com/ramya-rao-a/go-outline \ 20 | github.com/acroca/go-symbols \ 21 | golang.org/x/tools/cmd/guru \ 22 | golang.org/x/tools/cmd/gorename \ 23 | github.com/cweill/gotests/... \ 24 | github.com/fatih/gomodifytags \ 25 | github.com/josharian/impl \ 26 | github.com/davidrjenni/reftools/cmd/fillstruct \ 27 | github.com/haya14busa/goplay/cmd/goplay \ 28 | github.com/godoctor/godoctor \ 29 | github.com/go-delve/delve/cmd/dlv \ 30 | github.com/rogpeppe/godef \ 31 | golang.org/x/tools/cmd/goimports \ 32 | golang.org/x/lint/golint \ 33 | && go build -o $GOPATH/bin/gocode-gomod github.com/stamblerre/gocode 34 | 35 | # Clean up. 36 | RUN apt-get autoremove -y && apt-get clean -y \ 37 | && rm -rf /var/lib/apt/lists/* 38 | 39 | # Revert workaround of avoiding redundant error "debconf: delaying package configuration, since apt-utils is not installed". 40 | # See https://code.visualstudio.com/docs/remote/containers-advanced#_debconf-delaying-package-configuration-since-aptutils-is-not-installed. 41 | ENV DEBIAN_FRONTEND=dialog 42 | 43 | # Expose service ports. 44 | EXPOSE 8000 45 | -------------------------------------------------------------------------------- /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 2019 The Evengers 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go RESTful 2 | 3 | 🚀 A real world production-grade RESTful Web Services proof-of-concept project. 4 | 5 | ## Objectives 6 | 7 | - An optimized Go implementation follows [The Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html), provides mechanism to declare Entities, Use cases, and External Services (e.g. data access). 8 | 9 | - An optimized Go implementation provides mechanism to expose Entities and Use Cases as [RESTful Web Services](https://en.wikipedia.org/wiki/Representational_state_transfer). 10 | 11 | - An optimized Go implementation of Token-based [Authentication](https://en.wikipedia.org/wiki/Authentication) and [Authorization](https://en.wikipedia.org/wiki/Authorization). 12 | 13 | - An optimized Go implementation provides abstract mechanism to access [Relational Databases](https://en.wikipedia.org/wiki/Relational_database). 14 | 15 | - An optimized Go Development Environment with [Git](https://git-scm.com/), [Docker](https://www.docker.com/), [Go Modules](https://github.com/golang/go/wiki/Modules), Go Debuggers ([GDB](https://golang.org/doc/gdb)/[Delve](https://github.com/go-delve/delve)) and popular code editors ([VSCode](https://www.google.com/search?client=safari&rls=en&q=vscode&ie=UTF-8&oe=UTF-8)/[GoLand](https://www.jetbrains.com/go/)/[Vim](https://github.com/fatih/vim-go)). 16 | 17 | - An optimized CI/CD Solution with [Github Actions](https://github.com/features/actions) and [AWS](https://aws.amazon.com/). 18 | 19 | - An optimized Distribution Solution with [Github Releases](https://help.github.com/en/enterprise/2.16/user/articles/about-releases) and [Github Package Registry](https://help.github.com/en/articles/about-github-package-registry). 20 | 21 | - A scalable and highly-available Production Deployment Solution over [AWS](https://aws.amazon.com/) using [Terraform](https://www.terraform.io/). 22 | 23 | - An optimized Staging Environment replicating Production Environment for testing purposes. 24 | 25 | - An optimized Issues Tracking mechanism with [Github Project](https://github.com/features/project-management/), [Issues](https://help.github.com/en/articles/about-issues) and [Pull Requests](https://help.github.com/en/articles/about-pull-requests). 26 | 27 | - Continual improvements. 28 | 29 | ## Issues Tracking 30 | 31 | [![Issue Tracking](https://img.shields.io/static/v1?label=issue%20tracking&message=Github%20project&color=lightgrey)](https://github.com/the-evengers/go-restful/projects/1) 32 | [![Open issues](https://img.shields.io/github/issues/the-evengers/go-restful)](https://github.com/the-evengers/go-restful/issues) [![Closed issues](https://img.shields.io/github/issues-closed/the-evengers/go-restful)](https://github.com/the-evengers/go-restful/issues?q=is%3Aissue+is%3Aclosed) [![Open PRs](https://img.shields.io/github/issues-pr/the-evengers/go-restful)](https://github.com/the-evengers/go-restful/pulls) [![Closed PRs](https://img.shields.io/github/issues-pr-closed/the-evengers/go-restful)](https://github.com/the-evengers/go-restful/pulls?q=is%3Apr+is%3Aclosed) 33 | 34 | This project use Github project, issues and pull requests to manage and track issues. Refer to [this Github project](https://github.com/the-evengers/go-restful/projects/1) for further details. 35 | 36 | ## Development 37 | 38 | ### Requirements 39 | 40 | Local development machines need to have following tools installed and working properly: 41 | 42 | - [Docker](https:://www.docker.com) for running a full-time containerized development environment. 43 | 44 | - [Visual Studio Code](https://code.visualstudio.com) with [Remote - Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) for writing code with Intellisense, running and debugging code within containers. 45 | 46 | Windows users need to additionally have an Unix-shell emulator to be able to run utility scripts ([Git Bash](https://gitforwindows.org) is recommended). 47 | 48 | ### Usage 49 | 50 | #### Develop with Visual Studio Code 51 | 52 | With all of above requirements fullfiled, developers can experience a full-time local-quality VSCode-powered containerized development environment by just opening the repository in VSCode container mode. 53 | 54 | Go [here](docs/DEV-WITH-VSCODE.md) for further details. 55 | 56 | #### Develop without Visual Studio Code 57 | 58 | Without VSCode, developers will not be able to achieve a full-time local-quality VSCode-powered containerized development environment. However, if there's any reason that you can not or do not want to work with Visual Studio Code, you can still start a containerized development environment and start working on that or even build your own development solution on top of that. 59 | 60 | Go [here](docs/DEV-WITHOUT-VSCODE.md) for further details. 61 | 62 | #### Project structure 63 | 64 | Quick overview of project structure, components and their roles. 65 | 66 | ``` 67 | ├── 📁.vscode/ # VSCode configurations. 68 | ├── 📦common/ # Common, utility Go components. 69 | ├── 📁docs/ # Documentation & assets. 70 | ├── 📁scripts/ # Utility scripts. 71 | ├── 📦users/ # Users-related Go components. 72 | ├── 📄.devcontainer.json # VSCode Remote-Containers configuration. 73 | ├── 📄.gitignore 74 | ├── 📄Dockerfile # Instructions to build development Docker image. 75 | ├── 📄go.mod # Go module configuration. 76 | ├── 📄go.sum # Go module checksum/lock. 77 | ├── 📖LICENSE 78 | ├── 📖README.md 79 | ├── 🚀main.go # Application's main entry point. 80 | 81 | ``` 82 | 83 | ### License 84 | 85 | [![Apache License 2.0](https://img.shields.io/github/license/the-evengers/go-restful)](https://github.com/the-evengers/go-restful/blob/master/LICENSE) ![Copyright © The Evengers](https://img.shields.io/static/v1?label=copyright&message=The%20Evengers&color=lightgrey) 86 | 87 | Copyright © The Evengers. All rights reserved. 88 | 89 | This project is licensed under the [Apache License 2.0](https://github.com/the-evengers/go-restful/blob/master/LICENSE) and is available for free. 90 | -------------------------------------------------------------------------------- /common/errors.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import "fmt" 4 | 5 | // Errors is a collection of errors. 6 | type Errors []error 7 | 8 | func (errs Errors) Error() string { 9 | msgs := make([]string, len(errs)) 10 | for i, err := range errs { 11 | msgs[i] = err.Error() 12 | } 13 | return fmt.Sprint(msgs) 14 | } 15 | -------------------------------------------------------------------------------- /docs/DEV-WITH-VSCODE.md: -------------------------------------------------------------------------------- 1 | ## Development with Visual Studio Code 2 | 3 | With all of [those requirements](/README.md#requirements) fullfiled, developers can experience a full-time local-quality VSCode-powered containerized development environment by just opening the repository in VSCode container mode. 4 | 5 | To open the repository in VSCode (after cloning the repository into local development machines), developers can either: 6 | 7 | - Issue following command (with VSCode command line tool added to `PATH`): 8 | 9 | ``` shell 10 | code /path/to/this/repository 11 | ``` 12 | 13 | - Or open the repository using VSCode graphical user interface: 14 | 15 | - Select *File* → *Open* → *Browse The Repository*. 16 | 17 | - Or use default keyboard shortcut: *Command* + *O* (or *Ctrl* + *O* on Windows). 18 | 19 | Once the repository is opened, as the repository includes `.devcontainer.json`, VSCode will automatically ask you to reopen in container mode. 20 | 21 | VSCode ask to repoen in container 22 | 23 | Just select *Reopen in Container*, or if you've already opened the project in local mode and don't see the above prompt, you can issue the VSCode command (*View* → *Command Pallete* or press *F1*) *Remote-Containers: Reopen in Container* to achieve the same effect. 24 | 25 | For the first open, VSCode will automatically build an image based on `.devcontainer.json` and `Dockerfile`, the process may take a while. Latter opens will reuse the prebuilt image. 26 | 27 | Once the image was built successfully, VSCode will launch a container from that image and start setting up some essential stuff for it to work. After that, you're now connected to the container within your VSCode client, you can use every features of VSCode as is. 28 | 29 | - You can start writing code with Intellisense support. 30 | 31 | - You can run and debug the application by either selecting *Debug* → *Start Debugging* or using default keyboard shortcut *F5*. 32 | 33 | Note that the local workspace will be mounted to `/go/src/github.com/the-evengers/go-restful` within the container. 34 | -------------------------------------------------------------------------------- /docs/DEV-WITHOUT-VSCODE.md: -------------------------------------------------------------------------------- 1 | ## Development without Visual Studio Code 2 | 3 | Without VSCode, developers will not be able to achieve a full-time local-quality VSCode-powered containerized development environment. However, if there's any reason that you can not or do not want to work with Visual Studio Code, you can still start a containerized development environment and start working on that or even build your own development solution on top of that. 4 | 5 | To start the development container, issue following command: 6 | 7 | ``` shell 8 | ./scripts/start-devcontainer.sh 9 | ``` 10 | 11 | For the first run, the script will build an image based on `Dockerfile`, the process may take a while. Latter runs will reuse the prebuilt image. 12 | 13 | Once the image was built successfully, it will launch a container in interactive mode and mount the repository's root directory to `/go/src/github.com/the-evengers/go-restful` within the container, so that developers can make changes to the repository locally and have those changes automatically reflected into the container. 14 | 15 | In interactive mode within the container, developers can issue every `go` CLI commands, e.g: 16 | 17 | ``` shell 18 | # To start the application. 19 | go run main.go 20 | ``` 21 | -------------------------------------------------------------------------------- /docs/images/vscode-ask-reopen-in-container.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phuctm97/go-restful/a0e8a849e18aa415a50da91e42989bd353438363/docs/images/vscode-ask-reopen-in-container.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/the-evengers/go-restful 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/gorilla/mux v1.7.3 7 | github.com/stretchr/testify v1.4.0 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= 4 | github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= 5 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 6 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 7 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 8 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 9 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 11 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 12 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 13 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "github.com/gorilla/mux" 8 | ) 9 | 10 | func listUsers(w http.ResponseWriter, r *http.Request) { 11 | fmt.Fprintf(w, "List users\n") 12 | } 13 | 14 | func getUser(w http.ResponseWriter, r *http.Request) { 15 | vars := mux.Vars(r) 16 | fmt.Fprintf(w, "Get user %s\n", vars["userId"]) 17 | } 18 | 19 | func createUser(w http.ResponseWriter, r *http.Request) { 20 | fmt.Fprintf(w, "Create user\n") 21 | } 22 | 23 | func updateUser(w http.ResponseWriter, r *http.Request) { 24 | vars := mux.Vars(r) 25 | fmt.Fprintf(w, "Update user %s\n", vars["userId"]) 26 | } 27 | 28 | func deleteUser(w http.ResponseWriter, r *http.Request) { 29 | vars := mux.Vars(r) 30 | fmt.Fprintf(w, "Delete user %s\n", vars["userId"]) 31 | } 32 | 33 | func main() { 34 | // Configure routes. 35 | router := mux.NewRouter() 36 | router.HandleFunc("/users/", listUsers).Methods(http.MethodGet) 37 | router.HandleFunc("/users/", createUser).Methods(http.MethodPost) 38 | router.HandleFunc("/users/{userId}/", getUser).Methods(http.MethodGet) 39 | router.HandleFunc("/users/{userId}/", updateUser).Methods(http.MethodPut) 40 | router.HandleFunc("/users/{userId}/", deleteUser).Methods(http.MethodDelete) 41 | 42 | // Start HTTP server. 43 | if err := http.ListenAndServe(":8000", router); err != nil { 44 | log.Fatal(err) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /scripts/start-devcontainer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Exit immediately on failure. 4 | set -e 5 | 6 | # Derive local workspace's absolute path from script's path. 7 | LOCAL_WORKDIR=$(cd $(dirname $(dirname "${BASH_SOURCE[0]}")) >/dev/null 2>&1 && pwd) 8 | 9 | main() { 10 | # Variables. 11 | local image_tag=go-restful:dev 12 | local local_workdir=$LOCAL_WORKDIR 13 | local local_port=8000 14 | 15 | local container_name=go-restful-dev 16 | local container_workdir=/root/project 17 | local container_port=8000 18 | 19 | # Build image (if necessary). 20 | docker build --rm -t $image_tag $local_workdir 21 | 22 | # Start container. 23 | docker run --rm -it \ 24 | --name $container_name \ 25 | --volume $local_workdir:$container_workdir \ 26 | --workdir $container_workdir \ 27 | --publish $local_port:$container_port \ 28 | $image_tag 29 | } 30 | 31 | main 32 | -------------------------------------------------------------------------------- /users/constants.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // Errors. 8 | var ( 9 | ErrUsernameIsTooShort = errors.New("username must be at least 1-character length") 10 | ErrUsernameIsTooLong = errors.New("username must be at most 32-character length") 11 | ErrUsernameWasUsed = errors.New("username was used") 12 | ErrUsernameContainsInvalidChar = errors.New("username must contain only digits, underscores, dashes, dots and alphabetical letters") 13 | ErrUsernameBeginsWithInvalidChar = errors.New("username must begin with either underscore or an alphabetical letter") 14 | ErrEmailIsInvalid = errors.New("email is invalid") 15 | ErrEmailIsTooLong = errors.New("email must be at most 128-character length") 16 | ErrEmailWasUsed = errors.New("email was used") 17 | ErrFullNameIsTooShort = errors.New("full name must be at least 1-character length") 18 | ErrFullNameIsTooLong = errors.New("full name must be at most 128-character length") 19 | ErrBioIsTooLong = errors.New("bio must be at most 128-character length") 20 | ) 21 | -------------------------------------------------------------------------------- /users/entities.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | import ( 4 | "regexp" 5 | 6 | "github.com/the-evengers/go-restful/common" 7 | ) 8 | 9 | // User holds a user's data. 10 | type User struct { 11 | Username string 12 | Email string 13 | FullName string 14 | Bio string 15 | } 16 | 17 | // ValidateUser validates a user data and returns validation errors or nil. 18 | func ValidateUser(user *User) error { 19 | errs := make([]error, 0) 20 | 21 | // Validate username. 22 | if len(user.Username) < 1 { 23 | errs = append(errs, ErrUsernameIsTooShort) 24 | } 25 | if len(user.Username) > 32 { 26 | errs = append(errs, ErrUsernameIsTooLong) 27 | } 28 | if !regexContainsOnlyDigitsUnderscoreDashesDotsAlpha.MatchString(user.Username) { 29 | errs = append(errs, ErrUsernameContainsInvalidChar) 30 | } 31 | if !regexBeginsWithUnderscoreOrAlpha.MatchString(user.Username) { 32 | errs = append(errs, ErrUsernameBeginsWithInvalidChar) 33 | } 34 | 35 | // Validate email. 36 | if !regexIsEmail.MatchString(user.Email) { 37 | errs = append(errs, ErrEmailIsInvalid) 38 | } 39 | if len(user.Email) > 128 { 40 | errs = append(errs, ErrEmailIsTooLong) 41 | } 42 | 43 | // Validate full name. 44 | if len(user.FullName) < 1 { 45 | errs = append(errs, ErrFullNameIsTooShort) 46 | } 47 | if len(user.FullName) > 128 { 48 | errs = append(errs, ErrFullNameIsTooLong) 49 | } 50 | 51 | // Validate bio. 52 | if len(user.Bio) > 256 { 53 | errs = append(errs, ErrBioIsTooLong) 54 | } 55 | 56 | // Return errors or nil. 57 | if len(errs) == 0 { 58 | return nil 59 | } 60 | return common.Errors(errs) 61 | } 62 | 63 | // ValidateUserUnique validates whether user's username or email is valid and returns errors or nil. 64 | func ValidateUserUnique(userRepo UserRepository, user *User) error { 65 | errs := make([]error, 0) 66 | 67 | var exists bool 68 | var err error 69 | 70 | // Validate username. 71 | exists, err = userRepo.ExistsByUsername(user.Username) 72 | if err != nil { 73 | return err 74 | } 75 | if exists { 76 | errs = append(errs, ErrUsernameWasUsed) 77 | } 78 | 79 | // Validate email. 80 | exists, err = userRepo.ExistsByEmail(user.Email) 81 | if err != nil { 82 | return err 83 | } 84 | if exists { 85 | errs = append(errs, ErrEmailWasUsed) 86 | } 87 | 88 | // Return errors or nil. 89 | if len(errs) == 0 { 90 | return nil 91 | } 92 | return common.Errors(errs) 93 | } 94 | 95 | // Regular expressions. 96 | var ( 97 | regexContainsOnlyDigitsUnderscoreDashesDotsAlpha = regexp.MustCompile(`^[0-9a-zA-Z_\.\-]*$`) 98 | regexBeginsWithUnderscoreOrAlpha = regexp.MustCompile(`^[a-zA-Z_].*$`) 99 | regexIsEmail = regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`) 100 | ) 101 | -------------------------------------------------------------------------------- /users/entities_test.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestValidateUser(t *testing.T) { 9 | tests := []struct { 10 | user User 11 | errs []error 12 | }{ 13 | { 14 | User{ 15 | Username: "hasInvalidCh@r", 16 | Email: "invalidemail", 17 | FullName: "Good Full Name", 18 | }, 19 | []error{ErrUsernameContainsInvalidChar, ErrEmailIsInvalid}, 20 | }, 21 | { 22 | User{ 23 | Username: "1beginWithNumber", 24 | Email: "good@email.com", 25 | FullName: "", 26 | }, 27 | []error{ErrUsernameBeginsWithInvalidChar, ErrFullNameIsTooShort}, 28 | }, 29 | { 30 | User{ 31 | Username: "this-username_is.valid.but-too_long", 32 | Email: "invalid@email", 33 | FullName: "Good Full Name", 34 | }, 35 | []error{ErrUsernameIsTooLong, ErrEmailIsInvalid}, 36 | }, 37 | { 38 | User{ 39 | Username: "username.dot-dash_underscore", 40 | Email: "good@email.com", 41 | FullName: "Good Full Name", 42 | Bio: "Good Bio", 43 | }, 44 | nil, 45 | }, 46 | } 47 | 48 | for _, test := range tests { 49 | errs := ValidateUser(&test.user) 50 | if test.errs == nil { 51 | assert.Nil(t, errs) 52 | } else { 53 | assert.ElementsMatch(t, errs, test.errs) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /users/interfaces.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | // UserRepository abstracts accesses to users-related data. 4 | type UserRepository interface { 5 | ExistsByUsername(string) (bool, error) 6 | ExistsByEmail(string) (bool, error) 7 | } 8 | -------------------------------------------------------------------------------- /users/repositories.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | type mockUserRepository struct{} 4 | 5 | func (r *mockUserRepository) ExistsByUsername(username string) (bool, error) { 6 | if username == "existed" { 7 | return true, nil 8 | } 9 | return false, nil 10 | } 11 | 12 | func (r *mockUserRepository) ExistsByEmail(email string) (bool, error) { 13 | if email == "existed@gmail.com" { 14 | return true, nil 15 | } 16 | return false, nil 17 | } 18 | 19 | // NewMockUserRepository returns a new mock user repository. 20 | func NewMockUserRepository() UserRepository { 21 | return new(mockUserRepository) 22 | } 23 | --------------------------------------------------------------------------------