Project layout design influenced by standard go project layout
By using the Gos Tool
go install github.com/yaza-putu/gos@latest
If it's not accessible, try moving it to the global bin
mv ~/go/bin/gos /usr/local/bin
Create new project with one command
gos create --echo
git clone https://github.com/yaza-putu/golang-starter-api.git && cd golang-starter-api && rm -rf .git
-
install depedency
make tidy # or go mod tidy
-
initialize module name
make init module=your_module_name
-
copy environment dev, test and set app_status=test for .env.test
make config #or cp .env.example .env cp .env.example .env.test
-
generate key
make key
-
run dev mode
make serve
-
build
make build
-
run test
make gotest
-
make migration
make migration table="name_of_table"
-
run migration
make migrate-up
-
make seeder
make seeder name="name_of_seeder"
-
run seeder
make seed-up
You only need to set the env variable db_auto_migrate to true to enable this
db_auto_migrate=true
For this template using global variable for database connection and redis connection
- if you need mock database in unit test you can use
// import
import "github.com/yaza-putu/golang-starter-api/internal/database"
dbMock := ...
database.Mock(dbMock)
special setting connection gorm in unit test (mocking)
set SkipInitializeWithVersion to true
db, err := gorm.Open(mysql.New(mysql.Config{
...
SkipInitializeWithVersion: true,
}), &gorm.Config{})
- if you need mock redis in unit test you can use
// import redis client
import redis_client "github.com/yaza-putu/golang-starter-api/internal/pkg/redis"
redisMock := ...
redis_client.Mock(redisMock)
email : admin@mail.com
pass : Password1
- unique
type v struct {
Name string `validate:"unique=table_name:column_name"`
}
// ecample
type v struct {
Name string `validate:"unique=users:name"`
}
- unique with ignore
type v struct {
Name string `validate:"unique=table_name:column_name:ignore_with_field_name"`
ID string `validate:"required"`
}
// example
type v struct {
Name string `validate:"unique=users:name:ID"`
ID string `validate:"required" json:"id"`
}
type FileHandler struct {
File multipart.File `validate:"required,filetype=image/png image/jpeg image/jpg"`
}
fs := FileHandler{}
f, err := ctx.FormFile("file")
if err == nil {
// send file into FileHandler struct to validate
fs.File, err = f.Open()
if err != nil {
return err
}
}
// validate with custom validation from go-playground/validator
val, err := request.Validation(&fs)