1
0
mirror of https://github.com/raseels-repos/golang-saas-starter-kit.git synced 2025-06-15 00:15:15 +02:00

Update readmes for both repo and example project

This commit is contained in:
Lee Brown
2019-06-11 23:43:59 -08:00
parent 61fbe6d084
commit e000073b9c
5 changed files with 157 additions and 275 deletions

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,135 +1,69 @@
# SaaS Service
# SaaS Starter Kit Example Project
Copyright 2019, Geeks Accelerator
Copyright 2019, Geeks Accelerator
twins@geeksaccelerator.com
## Description
This is a project that provides a starter-kit for a REST based web service. It provides best practices around Go web services using POD architecture and design. It contains the following features:
The example project provides the ability clients to manage projects. New clients can sign up which creates an account and a user with role admin. Two basic roles are available for users: admins and users. Admins have the ability to perform all CRUD actions on projects and users. Those users with role user only have the ability to view projects and users.
* Minimal application web framework.
* Middleware integration.
* Database support using MongoDB.
* CRUD based pattern.
* Distributed logging and tracing.
* Testing patterns.
* User authentication.
* POD architecture with sidecars for metrics and tracing.
* Use of Docker, Docker Compose, and Makefiles.
* Vendoring dependencies with Modules, requires Go 1.11 or higher.
All business logic should be contained as a package outside both the web app and web API. This enables both the web app and web API to use the same API (Golang packages) with the only main difference between them is their response, HTML or JSON.
This project has the following example services:
* web api - Used to publically expose handlers
* web app - Display and render html.
* schema - Tool for initializing of db and schema migration.
## Local Installation
This project contains three services and uses 3rd party services:
* redis - key / value storage for sessions and other web data. Used only as emphemeral storage.
* postgres - transaction database for persitance of all data.
* datadog - metrics, logging, and tracing
Docker is required to run this software on your local machine.
An AWS account is required for the project to run because of the following dependancies on AWS:
* secret manager
* s3
Required for deploymenet:
* ECS Fargate
* RDS
* Route
### Getting the project
You can use the traditional `go get` command to download this project into your configured GOPATH.
```
$ go get -u gitlab.com/geeks-accelerator/oss/saas-starter-kit
```
### Go Modules
This project is using Go Module support for vendoring dependencies. We are using the `tidy` command to maintain the dependencies and make sure the project can create reproducible builds. This project assumes the source code will be inside your GOPATH within the traditional location.
```
cd $GOPATH/src/geeks-accelerator/oss/saas-starter-kit/example-project
GO111MODULE=on go mod tidy
```
It's recommended to set use at least go 1.12 and enable go modules.
```bash
echo "export GO111MODULE=on" >> ~/.bash_profile
```
### Installing Docker
Docker is a critical component to managing and running this project.
https://docs.docker.com/install/
If you are having problems installing docker reach out or jump on [Gopher Slack](http://invite.slack.golangbridge.org/) for help.
## Running The Project
There is a `docker-compose` file that knows how to build and run all the services. Each service has it's own a `dockerfile`.
There is a `docker-compose` file that knows how to build and run all the services. Each service has its own a `dockerfile`.
A `makefile` has also been provide to make building, running and testing the software easier.
### Building the project
Navigate to the root of the project and use the `makefile` to build all of the services.
```
$ cd $GOPATH/src/geeks-accelerator/oss/saas-starter-kit/example-project
$ make all
```
### Running the project
Navigate to the root of the project and use the `makefile` to run all of the services.
Navigate to the root of the project and first set your AWS configs. Copy `sample.env_docker_compose` to `.env_docker_compose` and update the credentials for docker-compose.
```
$ cd $GOPATH/src/geeks-accelerator/oss/saas-starter-kit/example-project
$ make up
$ cp sample.env_docker_compose .env_docker_compose
```
The `make up` command will leverage Docker Compose to run all the services, including the 3rd party services. The first time to run this command, Docker will download the required images for the 3rd party services.
Use the `docker-compose.yaml` to run all of the services, including the 3rd party services. The first time to run this command, Docker will download the required images for the 3rd party services.
```
$ docker-compose up
```
Default configuration is set which should be valid for most systems. Use the `docker-compose.yaml` file to configure the services differently using environment variables when necessary.
Default configuration is set which should be valid for most systems. Use the `docker-compose.yaml` file to configure the services differently is necessary. Email me if you have issues or questions.
### Stopping the project
You can hit <ctrl>C in the terminal window running `make up`. Once that shutdown sequence is complete, it is important to run the `make down` command.
You can hit <ctrl>C in the terminal window running `docker-compose up`. Once that shutdown sequence is complete, it is important to run the `docker-compose down` command.
```
$ <ctrl>C
$ make down
$ docker-compose down
```
Running `make down` will properly stop and terminate the Docker Compose session.
Running `docker-compose down` will properly stop and terminate the Docker Compose session.
## About The Project
The service provides record keeping for someone running a multi-family garage sale. Authenticated users can maintain a list of projects for sale.
## Web App
[cmd/web-app](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/tree/master/example-project/cmd/web-app)
Responsive web application that renders HTML using the `html/template` package from the standard library to enable direct interaction with clients and their users. It allows clients to sign up new accounts and provides user authentication with HTTP sessions. The web app relies on the Golang business logic packages developed to provide an API for internal development.
## Web API
[cmd/web-api](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/tree/master/example-project/cmd/web-api)
REST API available to clients for supporting deeper integrations. The API implements JWT authentication that renders results as JSON to clients. This API is not directly used by the web app to prevent locking the functionally needed internally for development of the web app to the same functionality exposed to clients. It’s believed that in the beginning, having to define an additional API for internal purposes is worth at additional effort as the internal API can handle more flexible updates. The API exposed to clients can then be maintained in a more rigid/structured process to manage client expectations.
### Making Requests
#### Initial User
To make a request to the service you must have an authenticated user. Users can be created with the API but an initial admin user must first be created. While the service is running you can create the initial user with the command `make admin`
```
$ make admin
```
This will create a user with email `admin@example.com` and password `gophers`.
To make a request to the service you must have an authenticated user. Users can be created with the API but an initial admin user must first be created. While the Web App service is running, signup to create a new account. The email and password used to create the initial account can be used to make API requests.
#### Authenticating
@ -139,7 +73,7 @@ Before any authenticated requests can be sent you must acquire an auth token. Ma
$ curl --user "admin@example.com:gophers" http://localhost:3000/v1/users/token
```
I suggest putting the resulting token in an environment variable like `$TOKEN`.
It’s best to put the resulting token in an environment variable like `$TOKEN`.
#### Authenticated Requests
@ -149,15 +83,33 @@ To make authenticated requests put the token in the `Authorization` header with
$ curl -H "Authorization: Bearer ${TOKEN}" http://localhost:3000/v1/users
```
## Schema
[cmd/schema](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/tree/master/example-project/cmd/schema)
Schema is a minimalistic database migration helper that can manually be invoked via CLI. It provides schema versioning and migration rollback. To support POD architecture, the schema for the entire project is defined globally and is located inside internal: [internal/schema](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/tree/master/example-project/internal/schema)
Keeping a global schema helps ensure business logic then can be decoupled across multiple packages. It’s a firm belief that data models should not be part of feature functionality. Globally defined structs are dangerous as they create large code dependencies. Structs for the same database table can be defined by package to help mitigate large code dependencies.
The example schema package provides two separate methods for handling schema migration.
[Migrations](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/blob/master/example-project/internal/schema/migrations.go)
List of direct SQL statements for each migration with defined version ID. A database table is created to persist executed migrations. Upon run of each schema migration run, the migraction logic checks the migration database table to check if it’s already been executed. Thus, schema migrations are only ever executed once. Migrations are defined as a function to enable complex migrations so results from query manipulated before being piped to the next query.
[Init Schema](https://gitlab.com/geeks-accelerator/oss/saas-starter-kit/blob/master/example-project/internal/schema/init_schema.go)
If you have a lot of migrations, it can be a pain to run all them, as example, when you are deploying a new instance of the app, in a clean database. To prevent this, use the initSchema function that will run if no migration was run before (in a new clean database). Remember to create everything here, all tables, foreign keys and what more you need in your app.
Another bonus with the globally defined schema allows testing to spin up database containers on demand include all the migrations. The testing package enables unit tests to programmatically execute schema migrations before running any unit tests.
## Development Notes
## Making db calls
Currently postgres is only supported for sqlxmigrate. MySQL should be easy to add after determing
better method for abstracting the create table and other SQL statements from the main
testing logic.
Postgres is only supported based on its dependency of sqlxmigrate. MySQL should be easy to add to sqlxmigrate after determining better method for abstracting the create table and other SQL statements from the main testing logic.
### bindvars
When making new packages that use sqlx, bind vars for mysql are `?` where as postgres is `$1`.
To database agnostic, sqlx supports using `?` for all queries and exposes the method `Rebind` to
To database agnostic, sqlx supports using `?` for all queries and exposes the method `Rebind` to
remap the placeholders to the correct database.
```go
@ -174,23 +126,18 @@ DD_EXPVAR=service_name=web-app env=dev url=http://web-app:4000/debug/vars|servic
```
## What's Next
We are in the process of writing more documentation about this code. Classes are being finalized as part of the Ultimate series.
## AWS Permissions
### AWS Permissions
Base required permissions
```
secretsmanager:CreateSecret
secretsmanager:GetSecretValue
secretsmanager:ListSecretVersionIds
secretsmanager:PutSecretValue
secretsmanager:UpdateSecret
secretsmanager:CreateSecret
secretsmanager:GetSecretValue
secretsmanager:ListSecretVersionIds
secretsmanager:PutSecretValue
secretsmanager:UpdateSecret
```
If cloudfront enabled for static files
@ -204,27 +151,6 @@ secretsmanager:DeleteSecret
```
## What's Next
### TODO:
* update makefile
additianal info required here in readme
need to copy sample.env_docker_compose to .env_docker_compose and defined your aws configs for docker-compose
need to add mid tracer for all requests
/*
ZipKin: http://localhost:9411
AddLoad: hey -m GET -c 10 -n 10000 "http://localhost:3000/v1/users"
expvarmon -ports=":3001" -endpoint="/metrics" -vars="requests,goroutines,errors,mem:memstats.Alloc"
*/
/*
Need to figure out timeouts for http service.
You might want to reset your DB_HOST env var during test tear down.
Service should start even without a DB running yet.
symbols in profiles: https://github.com/golang/go/issues/23376 / https://github.com/google/pprof/pull/366
*/
We are in the process of writing more documentation about this code.

View File

@ -1,115 +0,0 @@
SHELL := /bin/bash
all: keys web-api metrics tracer
keys:
go run ./cmd/sales-admin/main.go --cmd keygen
admin:
go run ./cmd/sales-admin/main.go --cmd useradd --user_email admin@example.com --user_password gophers
web-api:
docker build \
-t gcr.io/web-api/web-api-amd64:1.0 \
--build-arg PACKAGE_NAME=web-api \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
metrics:
docker build \
-t gcr.io/web-api/metrics-amd64:1.0 \
--build-arg PACKAGE_NAME=metrics \
--build-arg PACKAGE_PREFIX=sidecar/ \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
tracer:
docker build \
-t gcr.io/web-api/tracer-amd64:1.0 \
--build-arg PACKAGE_NAME=tracer \
--build-arg PACKAGE_PREFIX=sidecar/ \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
up:
docker-compose up
down:
docker-compose down
test:
cd "$$GOPATH/src/geeks-accelerator/oss/saas-starter-kit/example-project"
go test ./...
clean:
docker system prune -f
stop-all:
docker stop $(docker ps -aq)
remove-all:
docker rm $(docker ps -aq)
#===============================================================================
# GKE
config:
@echo Setting environment for web-api
gcloud config set project web-api
gcloud config set compute/zone us-central1-b
gcloud auth configure-docker
@echo ======================================================================
project:
gcloud projects create web-api
gcloud beta billing projects link web-api --billing-account=$(ACCOUNT_ID)
gcloud services enable container.googleapis.com
@echo ======================================================================
cluster:
gcloud container clusters create web-api-cluster --num-nodes=2 --machine-type=n1-standard-2
gcloud compute instances list
@echo ======================================================================
upload:
docker push gcr.io/web-api/web-api-amd64:1.0
docker push gcr.io/web-api/metrics-amd64:1.0
docker push gcr.io/web-api/tracer-amd64:1.0
@echo ======================================================================
database:
kubectl create -f gke-deploy-database.yaml
kubectl expose -f gke-expose-database.yaml --type=LoadBalancer
@echo ======================================================================
services:
kubectl create -f gke-deploy-web-api.yaml
kubectl expose -f gke-expose-web-api.yaml --type=LoadBalancer
@echo ======================================================================
shell:
kubectl exec -it pod-name --container name -- /bin/bash
@echo ======================================================================
status:
gcloud container clusters list
kubectl get nodes
kubectl get pods
kubectl get services web-api
@echo ======================================================================
delete:
kubectl delete services web-api
kubectl delete deployment web-api
gcloud container clusters delete web-api-cluster
gcloud projects delete web-api
docker image remove gcr.io/web-api/web-api-amd64:1.0
docker image remove gcr.io/web-api/metrics-amd64:1.0
docker image remove gcr.io/web-api/tracer-amd64:1.0
@echo ======================================================================