Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(script): add command to auto run and script #73

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ DB_PORT = 5432
NGINX_PORT=8080
GOLANG_PORT=8888
APP_ENV=localhost
JWT_SECRET=<your secret key>

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
Expand Down
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,18 @@ There are 2 ways to do running
go run main.go
```

## Run Migrations and Seeder
To run migrations and seed the database, use the following commands:
## Run Migrations, Seeder, and Script
To run migrations, seed the database, and execute a script while keeping the application running, use the following command:

```bash
go run main.go --migrate --seed
go run main.go --migrate --seed --run --script:example_script
```

- ``--migrate`` will apply all pending migrations.
- ``--seed`` will seed the database with initial data.
- ``--script:example_script`` will run the specified script (replace ``example_script`` with your script name).
- ``--run`` will ensure the application continues running after executing the commands above.

#### Migrate Database
To migrate the database schema
```bash
Expand All @@ -101,6 +106,15 @@ go run main.go --seed
```
This command will populate the database with initial data using the seeders defined in your application.

#### Script Run
To run a specific script:
```bash
go run main.go --script:example_script
```
Replace ``example_script`` with the actual script name in **script.go** at script folder

If you need the application to continue running after performing migrations, seeding, or executing a script, always append the ``--run`` option.

## What did you get?
By using this template, you get a ready-to-go architecture with pre-configured endpoints. The template provides a structured foundation for building your application using Golang with Clean Architecture principles.

Expand Down
30 changes: 28 additions & 2 deletions cmd/command.go → command/command.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package cmd
package command

import (
"log"
"os"
"strings"

"github.com/Caknoooo/go-gin-clean-starter/migrations"
"github.com/Caknoooo/go-gin-clean-starter/script"
"gorm.io/gorm"
)

func Commands(db *gorm.DB) {
func Commands(db *gorm.DB) bool {
var scriptName string

migrate := false
seed := false
run := false
scriptFlag := false

for _, arg := range os.Args[1:] {
if arg == "--migrate" {
Expand All @@ -19,6 +25,13 @@ func Commands(db *gorm.DB) {
if arg == "--seed" {
seed = true
}
if arg == "--run" {
run = true
}
if strings.HasPrefix(arg, "--script:") {
scriptFlag = true
scriptName = strings.TrimPrefix(arg, "--script:")
}
}

if migrate {
Expand All @@ -34,4 +47,17 @@ func Commands(db *gorm.DB) {
}
log.Println("seeder completed successfully")
}

if scriptFlag {
if err := script.Script(scriptName, db); err != nil {
log.Fatalf("error script: %v", err)
}
log.Println("script run successfully")
}

if run {
return true
}

return false
}
6 changes: 3 additions & 3 deletions controller/user_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (c *userController) Register(ctx *gin.Context) {
return
}

result, err := c.userService.RegisterUser(ctx.Request.Context(), user)
result, err := c.userService.Register(ctx.Request.Context(), user)
if err != nil {
res := utils.BuildResponseFailed(dto.MESSAGE_FAILED_REGISTER_USER, err.Error(), nil)
ctx.JSON(http.StatusBadRequest, res)
Expand Down Expand Up @@ -156,7 +156,7 @@ func (c *userController) Update(ctx *gin.Context) {
}

userId := ctx.MustGet("user_id").(string)
result, err := c.userService.UpdateUser(ctx.Request.Context(), req, userId)
result, err := c.userService.Update(ctx.Request.Context(), req, userId)
if err != nil {
res := utils.BuildResponseFailed(dto.MESSAGE_FAILED_UPDATE_USER, err.Error(), nil)
ctx.JSON(http.StatusBadRequest, res)
Expand All @@ -170,7 +170,7 @@ func (c *userController) Update(ctx *gin.Context) {
func (c *userController) Delete(ctx *gin.Context) {
userId := ctx.MustGet("user_id").(string)

if err := c.userService.DeleteUser(ctx.Request.Context(), userId); err != nil {
if err := c.userService.Delete(ctx.Request.Context(), userId); err != nil {
res := utils.BuildResponseFailed(dto.MESSAGE_FAILED_DELETE_USER, err.Error(), nil)
ctx.AbortWithStatusJSON(http.StatusBadRequest, res)
return
Expand Down
8 changes: 5 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"log"
"os"

"github.com/Caknoooo/go-gin-clean-starter/cmd"
"github.com/Caknoooo/go-gin-clean-starter/command"
"github.com/Caknoooo/go-gin-clean-starter/config"
"github.com/Caknoooo/go-gin-clean-starter/controller"
"github.com/Caknoooo/go-gin-clean-starter/middleware"
Expand All @@ -20,8 +20,10 @@ func main() {
defer config.CloseDatabaseConnection(db)

if len(os.Args) > 1 {
cmd.Commands(db)
return
flag := command.Commands(db)
if !flag {
return
}
}

var (
Expand Down
25 changes: 25 additions & 0 deletions script/example_script.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package script

import (
"fmt"

"gorm.io/gorm"
)

type (
ExampleScript struct {
db *gorm.DB
}
)

func NewExampleScript(db *gorm.DB) *ExampleScript {
return &ExampleScript{
db: db,
}
}

func (s *ExampleScript) Run() error {
// your script here
fmt.Println("example script running")
return nil
}
17 changes: 17 additions & 0 deletions script/script.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package script

import (
"errors"

"gorm.io/gorm"
)

func Script(scriptName string, db *gorm.DB) error {
switch scriptName {
case "example_script":
exampleScript := NewExampleScript(db)
return exampleScript.Run()
default:
return errors.New("script not found")
}
}
20 changes: 6 additions & 14 deletions service/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"html/template"
"os"
"strings"
"sync"
"time"

"github.com/Caknoooo/go-gin-clean-starter/constants"
Expand All @@ -21,14 +20,14 @@ import (

type (
UserService interface {
RegisterUser(ctx context.Context, req dto.UserCreateRequest) (dto.UserResponse, error)
Register(ctx context.Context, req dto.UserCreateRequest) (dto.UserResponse, error)
GetAllUserWithPagination(ctx context.Context, req dto.PaginationRequest) (dto.UserPaginationResponse, error)
GetUserById(ctx context.Context, userId string) (dto.UserResponse, error)
GetUserByEmail(ctx context.Context, email string) (dto.UserResponse, error)
SendVerificationEmail(ctx context.Context, req dto.SendVerificationEmailRequest) error
VerifyEmail(ctx context.Context, req dto.VerifyEmailRequest) (dto.VerifyEmailResponse, error)
UpdateUser(ctx context.Context, req dto.UserUpdateRequest, userId string) (dto.UserUpdateResponse, error)
DeleteUser(ctx context.Context, userId string) error
Update(ctx context.Context, req dto.UserUpdateRequest, userId string) (dto.UserUpdateResponse, error)
Delete(ctx context.Context, userId string) error
Verify(ctx context.Context, req dto.UserLoginRequest) (dto.UserLoginResponse, error)
}

Expand All @@ -45,19 +44,12 @@ func NewUserService(userRepo repository.UserRepository, jwtService JWTService) U
}
}

var (
mu sync.Mutex
)

const (
LOCAL_URL = "http://localhost:3000"
VERIFY_EMAIL_ROUTE = "register/verify_email"
)

func (s *userService) RegisterUser(ctx context.Context, req dto.UserCreateRequest) (dto.UserResponse, error) {
mu.Lock()
defer mu.Unlock()

func (s *userService) Register(ctx context.Context, req dto.UserCreateRequest) (dto.UserResponse, error) {
var filename string

_, flag, _ := s.userRepo.CheckEmail(ctx, nil, req.Email)
Expand Down Expand Up @@ -287,7 +279,7 @@ func (s *userService) GetUserByEmail(ctx context.Context, email string) (dto.Use
}, nil
}

func (s *userService) UpdateUser(ctx context.Context, req dto.UserUpdateRequest, userId string) (dto.UserUpdateResponse, error) {
func (s *userService) Update(ctx context.Context, req dto.UserUpdateRequest, userId string) (dto.UserUpdateResponse, error) {
user, err := s.userRepo.GetUserById(ctx, nil, userId)
if err != nil {
return dto.UserUpdateResponse{}, dto.ErrUserNotFound
Expand Down Expand Up @@ -316,7 +308,7 @@ func (s *userService) UpdateUser(ctx context.Context, req dto.UserUpdateRequest,
}, nil
}

func (s *userService) DeleteUser(ctx context.Context, userId string) error {
func (s *userService) Delete(ctx context.Context, userId string) error {
user, err := s.userRepo.GetUserById(ctx, nil, userId)
if err != nil {
return dto.ErrUserNotFound
Expand Down
Loading