Skip to content

Commit 6201474

Browse files
author
Vic Shóstak
authored
Merge pull request #8 from create-go-app/dev
Update README
2 parents 1a56d0b + bb9a356 commit 6201474

File tree

8 files changed

+116
-69
lines changed

8 files changed

+116
-69
lines changed

.dockerignore

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
.dockerignore
33
.editorconfig
44
.gitignore
5+
.env.example
56
Dockerfile
67
Makefile
78
LICENSE
8-
*.md
9+
**/*.md
10+
**/*_test.go
911

1012
# Folders
1113
.git/
1214
.github/
13-
.task/
14-
app/
15-
**/*_test.go
15+
build/

Makefile

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ migrate.force:
3232
docker.build:
3333
docker build -t net_http-go-template .
3434

35-
docker.run: docker.net_http docker.postgres
35+
docker.network:
36+
docker network inspect dev-network >/dev/null 2>&1 || \
37+
docker network create -d bridge dev-network
38+
39+
docker.run: docker.network docker.net_http docker.postgres
3640

3741
docker.stop:
3842
docker stop dev-net_http dev-postgres

README.md

Lines changed: 86 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,115 @@
11
# net/http backend template for [Create Go App CLI](https://github.com/create-go-app/cli)
22

3-
<img src="https://img.shields.io/badge/Go-1.11+-00ADD8?style=for-the-badge&logo=go" alt="go version" />&nbsp;<a href="https://gocover.io/github.com/create-go-app/net_http-go-template/pkg/apiserver" target="_blank"><img src="https://img.shields.io/badge/Go_Cover-49%25-success?style=for-the-badge&logo=none" alt="go cover" /></a>&nbsp;<a href="https://goreportcard.com/report/github.com/create-go-app/net_http-go-template" target="_blank"><img src="https://img.shields.io/badge/Go_report-A+-success?style=for-the-badge&logo=none" alt="go report" /></a>&nbsp;<img src="https://img.shields.io/badge/license-mit-red?style=for-the-badge&logo=none" alt="license" />
3+
<img src="https://img.shields.io/badge/Go-1.16+-00ADD8?style=for-the-badge&logo=go" alt="go version" />&nbsp;<a href="https://goreportcard.com/report/github.com/create-go-app/net_http-go-template" target="_blank"><img src="https://img.shields.io/badge/Go_report-A+-success?style=for-the-badge&logo=none" alt="go report" /></a>&nbsp;<img src="https://img.shields.io/badge/license-mit-red?style=for-the-badge&logo=none" alt="license" />
44

55
Package `net` provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets. Although the package provides access to low-level networking primitives.
66

77
Package [`net/http`](https://golang.org/pkg/net/http/) provides HTTP client and server implementations.
88

99
## ⚡️ Quick start
1010

11-
1. Create a new project:
11+
1. Create a new project with Fiber:
1212

1313
```bash
1414
cgapp create
15+
16+
# Choose a backend framework:
17+
# > net/http
18+
# Fiber
1519
```
1620

17-
2. Run project by this command:
21+
2. Run Docker container with database (_by default, for PostgreSQL_):
1822

1923
```bash
20-
make run
24+
make docker.postgres
2125
```
2226

23-
## ✅ Used packages
27+
3. Apply migrations:
2428

25-
- [gorilla/mux](https://github.com/gorilla/mux) `v1.7.4`
26-
- [go-yaml/yaml](https://github.com/go-yaml/yaml) `v2.3.0`
29+
```bash
30+
make migration.up user=<db_user> pass=<db_pass> host=<db_host> table=<db_table>
31+
```
2732

28-
## 🗄 Template structure
33+
4. Rename `.env.example` to `.env` and fill it with your environment values.
34+
35+
5. Run project by this command:
2936

3037
```bash
31-
.
32-
├── .dockerignore
33-
├── .editorconfig
34-
├── .gitignore
35-
├── Dockerfile
36-
├── Makefile
37-
├── go.mod
38-
├── go.sum
39-
├── main.go
40-
├── configs
41-
│ └── apiserver.yml
42-
├── static
43-
│ └── index.html
44-
└── pkg
45-
└── apiserver
46-
├── config.go
47-
├── config_test.go
48-
├── error_checker.go
49-
├── error_checker_test.go
50-
├── new_server.go
51-
├── new_server_test.go
52-
├── routes.go
53-
├── utils.go
54-
└── utils_test.go
55-
56-
4 directories, 17 files
38+
make run
5739
```
5840

41+
6. Go to API Docs page (Swagger): [localhost:5000/swagger/index.html](http://localhost:5000/swagger/index.html).
42+
43+
## 📦 Used packages
44+
45+
| Name | Version | Type |
46+
| --------------------------------------------------------------------- | --------- | ---------- |
47+
| [net/http](https://golang.org/pkg/net/http/) | `v1.16.0` | core |
48+
| [auth0/go-jwt-middleware](https://github.com/auth0/go-jwt-middleware) | `v1.0.0` | middleware |
49+
| [swaggo/http-swagger](https://github.com/swaggo/http-swagger) | `v1.0.0` | middleware |
50+
| [stretchr/testify](https://github.com/stretchr/testify) | `v1.7.0` | tests |
51+
| [dgrijalva/jwt-go](https://github.com/dgrijalva/jwt-go) | `v3.2.0` | auth |
52+
| [joho/godotenv](https://github.com/joho/godotenv) | `v1.3.0` | config |
53+
| [jmoiron/sqlx](https://github.com/jmoiron/sqlx) | `v1.3.1` | database |
54+
| [jackc/pgx](https://github.com/jackc/pgx) | `v4.10.1` | database |
55+
| [swaggo/swag](https://github.com/swaggo/swag) | `v1.7.0` | utils |
56+
| [google/uuid](https://github.com/google/uuid) | `v1.2.0` | utils |
57+
| [go-playground/validator](https://github.com/go-playground/validator) | `v10.4.1` | utils |
58+
59+
## 🗄 Template structure
60+
61+
### ./app
62+
63+
**Folder with business logic only**. This directory doesn't care about _what database driver you're using_ or _which caching solution your choose_ or any third-party things.
64+
65+
- `./app/controllers` folder for functional controllers (used in routes)
66+
- `./app/models` folder for describe business models and methods of your project
67+
- `./app/queries` folder for describe queries for models of your project
68+
- `./app/validators` folder for describe validators for models fields
69+
70+
### ./docs
71+
72+
**Folder with API Documentation**. This directory contains config files for auto-generated API Docs by Swagger.
73+
74+
### ./pkg
75+
76+
**Folder with project-specific functionality**. This directory contains all the project-specific code tailored only for your business use case, like _configs_, _middleware_, _routes_ or _utils_.
77+
78+
- `./pkg/configs` folder for configuration functions
79+
- `./pkg/middleware` folder for add middleware (Fiber built-in and yours)
80+
- `./pkg/routes` folder for describe routes of your project
81+
- `./pkg/utils` folder with utility functions (server starter, error checker, etc)
82+
83+
### ./platform
84+
85+
**Folder with platform-level logic**. This directory contains all the platform-level logic that will build up the actual project, like _setting up the database_ or _cache server instance_ and _storing migrations_.
86+
87+
- `./platform/database` folder with database setup functions (by default, PostgreSQL)
88+
- `./platform/migrations` folder with migration files (used with [golang-migrate/migrate](https://github.com/golang-migrate/migrate) tool)
89+
5990
## ⚙️ Configuration
6091

61-
```yaml
62-
# ./configs/apiserver.yml
63-
64-
# Server config
65-
server:
66-
host: 0.0.0.0
67-
port: 5000
68-
69-
# Database config
70-
database:
71-
host: 127.0.0.1
72-
port: 5432
73-
username: postgres
74-
password: 1234
75-
76-
# Static files config
77-
static:
78-
prefix: /
79-
path: ./static
92+
```ini
93+
# .env
94+
95+
# Server settings:
96+
SERVER_URL="0.0.0.0:5000"
97+
SERVER_EMAIL="no-reply@example.com"
98+
SERVER_EMAIL_PASSWORD="secret"
99+
100+
# JWT settings:
101+
JWT_SECRET_KEY="secret"
102+
JWT_REFRESH_KEY="refresh"
103+
104+
# Database settings:
105+
DB_SERVER_URL="host=localhost port=5432 user=postgres password=password dbname=postgres sslmode=disable"
106+
DB_MAX_CONNECTIONS=100
107+
DB_MAX_IDLE_CONNECTIONS=10
108+
DB_MAX_LIFETIME_CONNECTIONS=2
109+
110+
# SMTP severs settings:
111+
SMTP_SERVER="smtp.example.com"
112+
SMTP_PORT=25
80113
```
81114

82115
## ⚠️ License

app/controllers/user_controller.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,9 @@ func GetUsers(w http.ResponseWriter, r *http.Request) {
7171
// @Success 200 {object} models.User
7272
// @Router /api/public/user/{id} [get]
7373
func GetUser(w http.ResponseWriter, r *http.Request) {
74-
// Define content type.
74+
// Define content type and CORS.
7575
w.Header().Set("Content-Type", "application/json")
76+
w.Header().Set("Access-Control-Allow-Origin", "*")
7677

7778
// Catch user ID from URL.
7879
id, err := uuid.Parse(r.URL.Query().Get("id"))
@@ -130,8 +131,9 @@ func GetUser(w http.ResponseWriter, r *http.Request) {
130131
// @Success 200 {object} models.User
131132
// @Router /api/private/user [post]
132133
func CreateUser(w http.ResponseWriter, r *http.Request) {
133-
// Define content type.
134+
// Define content type and CORS.
134135
w.Header().Set("Content-Type", "application/json")
136+
w.Header().Set("Access-Control-Allow-Origin", "*")
135137

136138
// Get now time.
137139
now := time.Now().Unix()
@@ -235,8 +237,9 @@ func CreateUser(w http.ResponseWriter, r *http.Request) {
235237
// @Success 200 {object} models.User
236238
// @Router /api/private/user [patch]
237239
func UpdateUser(w http.ResponseWriter, r *http.Request) {
238-
// Define content type.
240+
// Define content type and CORS.
239241
w.Header().Set("Content-Type", "application/json")
242+
w.Header().Set("Access-Control-Allow-Origin", "*")
240243

241244
// Get now time.
242245
now := time.Now().Unix()
@@ -347,8 +350,9 @@ func UpdateUser(w http.ResponseWriter, r *http.Request) {
347350
// @Success 200 {string} string "ok"
348351
// @Router /api/private/user [delete]
349352
func DeleteUser(w http.ResponseWriter, r *http.Request) {
350-
// Define content type.
353+
// Define content type and CORS.
351354
w.Header().Set("Content-Type", "application/json")
355+
w.Header().Set("Access-Control-Allow-Origin", "*")
352356

353357
// Get now time.
354358
now := time.Now().Unix()

main.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ func main() {
3131
routes.PrivateRoutes(router)
3232
routes.SwaggerRoutes(router)
3333

34-
// Register API routes.
34+
// Register middleware.
35+
router.Use(mux.CORSMethodMiddleware(router)) // enable CORS
36+
37+
// Initialize server.
3538
server := configs.ServerConfig(router)
3639

3740
// Start API server.

pkg/routes/private_routes.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ func PrivateRoutes(router *mux.Router) {
2020
deleteUser := jwtProtected.Handler(http.HandlerFunc(controllers.DeleteUser))
2121

2222
// Routes for POST method:
23-
router.Handle("/api/private/user", createUser).Methods("POST") // create user by ID
23+
router.Handle("/api/private/user", createUser).Methods(http.MethodPost) // create user by ID
2424

2525
// Routes for PATCH method:
26-
router.Handle("/api/private/user", updateUser).Methods("PATCH") // update user by ID
26+
router.Handle("/api/private/user", updateUser).Methods(http.MethodPatch) // update user by ID
2727

2828
// Routes for DELETE method:
29-
router.Handle("/api/private/user", deleteUser).Methods("DELETE") // delete user by ID
29+
router.Handle("/api/private/user", deleteUser).Methods(http.MethodDelete) // delete user by ID
3030
}

pkg/routes/public_routes.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
package routes
22

33
import (
4+
"net/http"
5+
46
"github.com/create-go-app/net_http-go-template/app/controllers"
57
"github.com/gorilla/mux"
68
)
79

810
// PublicRoutes func for describe group of public routes.
911
func PublicRoutes(router *mux.Router) {
1012
// Routes for GET method:
11-
router.HandleFunc("/api/public/user/{id}", controllers.GetUser).Methods("GET") // get one user by ID
12-
router.HandleFunc("/api/public/users", controllers.GetUsers).Methods("GET") // Get list of all users
13+
router.HandleFunc("/api/public/user/{id}", controllers.GetUser).Methods(http.MethodGet) // get one user by ID
14+
router.HandleFunc("/api/public/users", controllers.GetUsers).Methods(http.MethodGet) // Get list of all users
1315
}

pkg/routes/swagger_routes.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package routes
22

33
import (
4+
"net/http"
45
"os"
56

67
"github.com/gorilla/mux"
@@ -19,5 +20,5 @@ func SwaggerRoutes(router *mux.Router) {
1920
)
2021

2122
// Routes for GET method:
22-
router.PathPrefix("/swagger/").Handler(getSwagger).Methods("GET") // get one user by ID
23+
router.PathPrefix("/swagger/").Handler(getSwagger).Methods(http.MethodGet) // get one user by ID
2324
}

0 commit comments

Comments
 (0)