Skip to content

Commit

Permalink
chore: new golang rest api template
Browse files Browse the repository at this point in the history
  • Loading branch information
vdhieu committed Jul 4, 2022
1 parent ad2f972 commit fd9d874
Show file tree
Hide file tree
Showing 84 changed files with 3,310 additions and 4,964 deletions.
12 changes: 0 additions & 12 deletions .editorconfig

This file was deleted.

17 changes: 17 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
SERVICE_NAME=api
PORT=8100
BASE_URL=http://localhost:8100
# DB config
ACCESS_TOKEN_TTL=30
DB_HOST="127.0.0.1"
DB_PORT="54321"
DB_USER="postgres"
DB_PASS="postgres"
DB_NAME="db_local"

ALLOWED_ORIGINS="https://*.dwarves.foundation/;https://*.vercel.app"
ENV=dev
JWT_SECRET=sample_secret

SENTRY_DSN=''
VERSION=1.0.0
22 changes: 0 additions & 22 deletions .eslintrc.js

This file was deleted.

16 changes: 16 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
**What does this PR do?**

- [x] My bugfix

**How to test**

- Create a detailed description of what you need to do to set this PR up. ie: Does it need migrations? Do you need to install something?
- Create a step by step list of what the engineer needs to do to test.

**Edge cases**

- What are the edge cases that you might see in this PR?

**Media (Loom or gif)**

- Insert media here (if applicable)
19 changes: 19 additions & 0 deletions .github/workflows/ci-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
on: [pull_request]

jobs:
ci-test:
runs-on: ubuntu-latest
name: CI testing
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: "^1.18.3"

- name: Init Test DB
run: make setup && make init && make migrate-up
env:
GOPATH: "/home/runner/go"

- name: Run Test Cases
run: make test
12 changes: 12 additions & 0 deletions .github/workflows/commitlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: Lint Commit Messages
on: [pull_request]

jobs:
commitlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0

- uses: wagoid/commitlint-github-action@v2
40 changes: 40 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
- main
pull_request:
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.18
- uses: actions/checkout@v3

- name: generating mock
run: go install github.com/golang/mock/[email protected] && go install github.com/vektra/mockery/v2@latest && make mock

- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: latest

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
args: --issues-exit-code=0

# Optional: show only new issues if it's a pull request. The default value is `false`.
only-new-issues: true
24 changes: 23 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
vendor/

# Go workspace file
go.work
.DS_Store
node_modules
*.log
.env
.vscode

mock_*
mocks
23 changes: 23 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
FROM golang:1.17
RUN mkdir /build
WORKDIR /build
COPY . .

ENV GOOS=linux GOARCH=amd64 CGO_ENABLED=0
RUN go install -v ./...
RUN go install -v github.com/rubenv/sql-migrate/sql-migrate@latest

FROM alpine:3.15.0
ARG DEFAULT_PORT
RUN apk --no-cache add ca-certificates
WORKDIR /

COPY --from=0 /go/bin/* /usr/bin/
COPY template /srv/neko/template
COPY migrations /migrations
COPY dbconfig.yml /
## config for timezone
COPY --from=0 /usr/share/zoneinfo /usr/share/zoneinfo
EXPOSE ${DEFAULT_PORT}

CMD [ "server" ]
62 changes: 62 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
APP_NAME=api
DEFAULT_PORT=8100
.PHONY: setup init build dev test db-migrate-up db-migrate-down

setup:
go install github.com/rubenv/sql-migrate/...@latest
go install github.com/golang/mock/[email protected]
go install github.com/vektra/mockery/v2@latest
cp .env.sample .env
make mock
make init

init:
make remove-infras
docker-compose up -d
@echo "Waiting for database connection..."
@while ! docker exec db_local pg_isready -h localhost -p 5432 > /dev/null; do \
sleep 1; \
done
make migrate-up
make seed-db

remove-infras:
docker-compose stop; docker-compose rm -f

build:
env GOOS=darwin GOARCH=amd64 go build -o bin ./...

dev:
go run ./cmd/server/main.go

test:
make mock
@PROJECT_PATH=$(shell pwd) go test -coverprofile=c.out -failfast -timeout 5m ./...


migrate-new:
sql-migrate new -env=local ${name}

migrate-up:
sql-migrate up -env=local

migrate-down:
sql-migrate down -env=local

docker-build:
docker build \
--build-arg DEFAULT_PORT="${DEFAULT_PORT}" \
-t ${APP_NAME}:latest .

seed-db:
@docker cp data/seed/seed.sql db_local:/seed.sql
@docker exec -t db_local sh -c "PGPASSWORD=postgres psql -U postgres -d db_local -f /seed.sql"

reset-db:
make init
make migrate-up
make seed-db

mock:
mockery --dir pkg/entities --all --recursive --keeptree
mockery --dir pkg/repo --all --recursive --keeptree
96 changes: 88 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,103 @@
# template-go

> Template for scaffolding your next Go http server project, based on [gokit](https://github.com/go-kit/kit).
> Template for scaffolding your next Go http server project
## Project structure

```
.
├── cmd
│ └── server // index entry point
├── data
│ ├── migrations // database migration
│ └── seed // initial data seed
├── mocks // generated mocks for testing
└── pkg
├── config // app configs, singleton get via config.GetConfig()
├── consts // app constant
├── entities // app bushiness logic
├── handlers // app handles
│ └── v1 // versioning v1
├── middleware // route middleware: auth
├── model // api modal, shared across the app
├── monitoring // logging package
├── repo
│ └── user
│ └── testdata // contains seed data for repo testing
├── routes // all rest api routes
│ └── v1.go // versioning v1
└── util // contains shared utilities
└── testutil // helper for db testing
```

## Usage

Install [SAO](https://github.com/egoist/sao) first.
### Available commands

**Dev**

```bash
yarn global add sao
# or
npm i -g sao
```
# only need run once
make setup
# start local server
make dev
### From git
# build binary
make build
# run all unit test
make test
```

**Migration**

```bash
sao dwarvesf/template-go my-project
# create a new migration
make migration-new name=example-alter-table

# apply new migrations
make migrate-up

# rollback a migration version
make migrate-down

```

### Monitoring

- Get logger instance

```go
import "github.com/dwarvesf/go-template/pkg/monitoring"

m := monitoring.FromContext(ctx)
```

- Do logging in handlers and entities package

- Log string format `[package.Function] invokingMethod(param1, param2=%v)`

```go
// example
m.Errorf(err, "[entity.LoginUser] GetUserByEmail(ctx, email=%v)", email)

m.Infof("[entity.LoginUser] GetUserByEmail(ctx, email=%v)", email)

```

### Testing

- Use mockery to generate mock for testing
- Command: `make mock`
- Repository testing (DB testing) required an docker DB instance running
- check example in `repo/user` for db integration testing
- sql seed file in testdata
- the seed file loaded by testutils

## License

MIT © [dwarvesf](github.com/dwarvesf)
24 changes: 0 additions & 24 deletions circle.yml

This file was deleted.

Loading

0 comments on commit fd9d874

Please sign in to comment.