diff --git a/README.md b/README.md index 8df9d4d3a..9aeeee6d4 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,50 @@ ### Requirements - Implement one single API which accepts a todo task and records it - - There is a maximum **limit of N tasks per user** that can be added **per day**. - - Different users can have **different** maximum daily limit. + - There is a maximum **limit of N tasks per user** that can be added **per day**. + - Different users can have **different** maximum daily limit. - Write integration (functional) tests - Write unit tests - Choose a suitable architecture to make your code simple, organizable, and maintainable - Write a concise README - - How to run your code locally? - - A sample “curl” command to call your API - - How to run your unit tests locally? - - What do you love about your solution? - - What else do you want us to know about however you do not have enough time to complete? + - How to run your code locally? + - A sample “curl” command to call your API + - How to run your unit tests locally? + - What do you love about your solution? + - What else do you want us to know about however you do not have enough time to complete? -### Notes +#### How to run -- We're using Golang at Manabie. **However**, we encourage you to use the programming language that you are most comfortable with because we want you to **shine** with all your skills and knowledge. +`Simply run the main.exe in build folder` -### How to submit your solution? +#### Test user -- Fork this repo and show us your development progress via a PR +Username: `dung` -### Interesting facts about Manabie +Password: `dung1234` -- Monthly there are about 2 million lines of code changes (inserted/updated/deleted) committed into our GitHub repositories. To avoid **regression bugs**, we write different kinds of **automated tests** (unit/integration (functionality)/end2end) as parts of the definition of done of our assigned tasks. -- We nurture the cultural values: **knowledge sharing** and **good communication**, therefore good written documents and readable, organizable, and maintainable code are in our blood when we build any features to grow our products. -- We have **collaborative** culture at Manabie. Feel free to ask trieu@manabie.com any questions. We are very happy to answer all of them. +#### Sample CURL: -Thank you for spending time to read and attempt our take-home assessment. We are looking forward to your submission. +`curl --location --request POST 'localhost:8800/api/togo/v1/task' \ +--header 'Content-Type: application/json' \ +--data-raw '{ +"content": "Task 1", +"user_id": 1, +"date": "11-12-2022" +}'` + +#### "date" must in type dd-mm-yyyy + +#### How to run test + +simple change dir to api_test folder and edit some date to make sure if it not duplicated and then + +`go test -v -run TestCreateTask ` + +or + +`go test` + +#### My solution is using gorm with support a lot of types database, so it is much easier to get data which relation + +#### A lot of things to do to enhance this (like cache database to avoid data reading time, doing pagination) diff --git a/api_test/api_test.go b/api_test/api_test.go new file mode 100644 index 000000000..a6a42c005 --- /dev/null +++ b/api_test/api_test.go @@ -0,0 +1,130 @@ +package api_test + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "io/ioutil" + "net/http" + "strconv" + "testing" + "togo-thdung002/entities" +) + +var ( + baseURL string = "http://localhost:8800/api/togo/v1" +) + +func TestCreateUser(t *testing.T) { + user := entities.User{ + Username: "dung", + Password: "dung123", + Limit: 15, + } + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(user) + if err != nil { + t.Log(err) + t.FailNow() + } + + request, _ := http.NewRequest(http.MethodPost, baseURL+"/user/register", &buf) + request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + resp, err := http.DefaultClient.Do(request) + if err != nil { + fmt.Println(err) + t.FailNow() + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + t.FailNow() + } + response := new(interface{}) + err = json.Unmarshal(body, response) + if err != nil { + t.Fail() + } + t.Log(*response) + + assert.Equal(t, 200, resp.StatusCode) + +} + +func TestCreateTask(t *testing.T) { + task := entities.Task{ + Content: "Task number 1", + UserID: 1, + Date: "25-06-2022", + } + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(task) + if err != nil { + t.Log(err) + t.FailNow() + } + + request, _ := http.NewRequest(http.MethodPost, baseURL+"/task", &buf) + request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + resp, err := http.DefaultClient.Do(request) + if err != nil { + fmt.Println(err) + t.FailNow() + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + t.FailNow() + } + response := new(interface{}) + err = json.Unmarshal(body, response) + if err != nil { + t.Fail() + } + t.Log(*response) + + assert.Equal(t, 200, resp.StatusCode) + +} + +func TestCreateBatchTask(t *testing.T) { + //create batch task to get error + for i := 1; i <= 10; i++ { + task := entities.Task{ + Content: "Task number " + strconv.Itoa(i), + UserID: 1, + Date: "15-07-2022", + } + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(task) + if err != nil { + t.Log(err) + t.FailNow() + } + request, _ := http.NewRequest(http.MethodPost, baseURL+"/task", &buf) + request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + resp, err := http.DefaultClient.Do(request) + if err != nil { + fmt.Println(err) + t.FailNow() + } + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + t.FailNow() + } + response := new(interface{}) + err = json.Unmarshal(body, response) + if err != nil { + t.Fail() + } + t.Log(*response) + assert.Equal(t, 200, resp.StatusCode) + + } + +} diff --git a/build/config/config.go b/build/config/config.go new file mode 100644 index 000000000..8b2eda72b --- /dev/null +++ b/build/config/config.go @@ -0,0 +1,47 @@ +package config + +import ( + "encoding/json" + log "github.com/sirupsen/logrus" + "io/ioutil" +) + +type Config struct { + API struct { + Listen string `json:"listen"` + DBAddress string `json:"db"` + } `json:"api"` +} + +func getConfigFromFile(filename string) ([]byte, error) { + data, err := ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + return data, nil +} + +func decodeLocalConf(data []byte) (*Config, error) { + config := &Config{} + + // try to decode json first and yaml in the next step + if err := json.Unmarshal(data, &config); err != nil { + return nil, err + } + // validate config + //config.Prefix = strings.TrimSuffix(config.Prefix, "/") + return config, nil +} + +func LoadConfig(filename string) (*Config, error) { + + log.Info("Loading configuration from ", filename) + + confData, jerr := getConfigFromFile(filename) + if jerr != nil { + log.Fatal("Failed to load configuration: ", jerr) + return nil, jerr + } + + return decodeLocalConf(confData) +} diff --git a/build/config/config.json b/build/config/config.json new file mode 100644 index 000000000..277c4a272 --- /dev/null +++ b/build/config/config.json @@ -0,0 +1,6 @@ +{ + "api": { + "listen": ":8800", + "db": "togo.db" + } +} diff --git a/build/togo.db b/build/togo.db new file mode 100644 index 000000000..3b28f0b9b Binary files /dev/null and b/build/togo.db differ diff --git a/config/config.go b/config/config.go new file mode 100644 index 000000000..8b2eda72b --- /dev/null +++ b/config/config.go @@ -0,0 +1,47 @@ +package config + +import ( + "encoding/json" + log "github.com/sirupsen/logrus" + "io/ioutil" +) + +type Config struct { + API struct { + Listen string `json:"listen"` + DBAddress string `json:"db"` + } `json:"api"` +} + +func getConfigFromFile(filename string) ([]byte, error) { + data, err := ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + return data, nil +} + +func decodeLocalConf(data []byte) (*Config, error) { + config := &Config{} + + // try to decode json first and yaml in the next step + if err := json.Unmarshal(data, &config); err != nil { + return nil, err + } + // validate config + //config.Prefix = strings.TrimSuffix(config.Prefix, "/") + return config, nil +} + +func LoadConfig(filename string) (*Config, error) { + + log.Info("Loading configuration from ", filename) + + confData, jerr := getConfigFromFile(filename) + if jerr != nil { + log.Fatal("Failed to load configuration: ", jerr) + return nil, jerr + } + + return decodeLocalConf(confData) +} diff --git a/config/config.json b/config/config.json new file mode 100644 index 000000000..277c4a272 --- /dev/null +++ b/config/config.json @@ -0,0 +1,6 @@ +{ + "api": { + "listen": ":8800", + "db": "togo.db" + } +} diff --git a/const/errors.go b/const/errors.go new file mode 100644 index 000000000..981e2b7b1 --- /dev/null +++ b/const/errors.go @@ -0,0 +1,12 @@ +package _const + +import "errors" + +var ( + ErrOnCreateUser = errors.New("Create user fail") + ErrOnCreateTask = errors.New("Create task fail") + ErrLimitedTask = errors.New("Reach limit task") + ErrUserNotFound = errors.New("User not found") + ErrDateType = errors.New("Date type not right") + ErrValidate = errors.New("Validate fail") +) diff --git a/controllers/api.go b/controllers/api.go new file mode 100644 index 000000000..b901ef3a1 --- /dev/null +++ b/controllers/api.go @@ -0,0 +1,37 @@ +package controllers + +import ( + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "net/http" +) + +func (ctrl *Controller) loadMux() { + e := echo.New() + + e.Use(middleware.RateLimiter(middleware.NewRateLimiterMemoryStore(1000))) + e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ + Skipper: middleware.DefaultSkipper, + AllowOrigins: []string{"*"}, + AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, + AllowCredentials: true, + })) + + apiv1 := e.Group("/api") + togov1 := apiv1.Group("/togo/v1") + { + task := togov1.Group("/task") + { + task.GET("", apiGetTask(ctrl)) + task.POST("", apiPostTask(ctrl)) + } + } + { + user := togov1.Group("/user") + { + user.POST("/register", apiPostUser(ctrl)) + } + } + ctrl.e = e + +} diff --git a/controllers/controller.go b/controllers/controller.go new file mode 100644 index 000000000..7ca4ea9bd --- /dev/null +++ b/controllers/controller.go @@ -0,0 +1,68 @@ +package controllers + +import ( + "context" + "github.com/labstack/echo/v4" + log "github.com/sirupsen/logrus" + "gorm.io/gorm" + "net/http" + "sync" + "time" + "togo-thdung002/config" + "togo-thdung002/entities/sqlite" +) + +type Controller struct { + e *echo.Echo + sync.Mutex + conf *config.Config + db *sqlite.LiteDB +} + +func NewController(conf *config.Config, sqlitedb *gorm.DB) *Controller { + db := sqlite.NewDB(sqlitedb) + + ctrl := Controller{ + db: db, + conf: conf, + } + ctrl.loadMux() + log.Infof("INF: Loading API Listener on %s\n", ":8800") + + return &ctrl +} +func (ctrl *Controller) Load() error { + ctrl.Lock() + defer ctrl.Unlock() + return nil +} + +// Start is non-blocking +func (ctrl *Controller) Start() { + ctrl.Lock() + defer ctrl.Unlock() +} + +// Stop is non-blocking +func (ctrl *Controller) Stop() { + ctrl.Lock() + defer ctrl.Unlock() +} + +func (ctrl *Controller) ListenAndServe() error { + + apiServer := &http.Server{ + Addr: ctrl.conf.API.Listen, + ErrorLog: nil, + ReadTimeout: 5 * time.Minute, + WriteTimeout: 5 * time.Minute, + } + ctrl.e.HideBanner = false + ctrl.e.Debug = false + return ctrl.e.StartServer(apiServer) +} + +func (ctrl *Controller) Shutdown(ctx context.Context) error { + ctrl.e.Shutdown(ctx) + return nil +} diff --git a/controllers/task_handler.go b/controllers/task_handler.go new file mode 100644 index 000000000..72412616c --- /dev/null +++ b/controllers/task_handler.go @@ -0,0 +1,75 @@ +package controllers + +import ( + "encoding/json" + "github.com/labstack/echo/v4" + log "github.com/sirupsen/logrus" + "io/ioutil" + "net/http" + "strconv" + _const "togo-thdung002/const" + "togo-thdung002/entities" + "togo-thdung002/entities/response" + "togo-thdung002/utils" +) + +func apiGetTask(s *Controller) echo.HandlerFunc { + return echo.HandlerFunc(func(c echo.Context) error { + var resp response.Response + userID := c.QueryParam("userid") + id, err := strconv.Atoi(userID) + if err != nil { + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + tasks, err := s.db.GetTaskFilterBy(uint(id), "") + if err != nil { + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + + return c.JSON(http.StatusOK, resp.Success(tasks)) + }) +} + +func apiPostTask(s *Controller) echo.HandlerFunc { + return echo.HandlerFunc(func(c echo.Context) error { + var resp response.Response + body, err := ioutil.ReadAll(c.Request().Body) + if err != nil { + log.Error("Error on read body request", err) + return c.JSON(http.StatusBadRequest, resp.Error(err)) + } + var task entities.Task + err = json.Unmarshal(body, &task) + if err != nil { + log.Error("Error on unmarshal body to struct", err) + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + if err := task.Validate(); err != nil { + log.Error("Error on validate struct", err) + return c.JSON(http.StatusInternalServerError, resp.Error(_const.ErrValidate)) + } + if task.UserID == 0 { + log.Error("User not found", err) + return c.JSON(http.StatusInternalServerError, resp.Error(_const.ErrUserNotFound)) + } + if ok := utils.IsDateValue(task.Date); !ok { + log.Error("Date type is not right - make sure it is dd-mm-yyyy") + return c.JSON(http.StatusInternalServerError, resp.Error(_const.ErrDateType)) + } + tasks, err := s.db.GetTaskFilterBy(task.UserID, task.Date) + if err != nil { + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + user, err := s.db.GetUser(task.UserID) + if len(tasks) > user.Limit-1 { + return c.JSON(http.StatusInternalServerError, resp.Error(_const.ErrLimitedTask)) + } + + createdID, err := s.db.CreateTask(&task) + if err != nil { + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + + return c.JSON(http.StatusOK, resp.Success(createdID)) + }) +} diff --git a/controllers/user_handler.go b/controllers/user_handler.go new file mode 100644 index 000000000..7712665cc --- /dev/null +++ b/controllers/user_handler.go @@ -0,0 +1,33 @@ +package controllers + +import ( + "encoding/json" + "github.com/labstack/echo/v4" + log "github.com/sirupsen/logrus" + "io/ioutil" + "net/http" + "togo-thdung002/entities" + "togo-thdung002/entities/response" +) + +func apiPostUser(s *Controller) echo.HandlerFunc { + return echo.HandlerFunc(func(c echo.Context) error { + var resp response.Response + body, err := ioutil.ReadAll(c.Request().Body) + if err != nil { + log.Error("Error on read body request", err) + return c.JSON(http.StatusBadRequest, resp.Error(err)) + } + var user entities.User + err = json.Unmarshal(body, &user) + if err != nil { + log.Error("Error on unmarshal body to struct", err) + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + createdID, err := s.db.CreateUser(&user) + if err != nil { + return c.JSON(http.StatusInternalServerError, resp.Error(err)) + } + return c.JSON(http.StatusOK, resp.Success(createdID)) + }) +} diff --git a/entities/request/request.go b/entities/request/request.go new file mode 100644 index 000000000..fea223e03 --- /dev/null +++ b/entities/request/request.go @@ -0,0 +1,6 @@ +package request + +type UserRequest struct { + Username string ` json:"username" validate:"required,gte=0,lte=256" ` + Password string ` json:"password" validate:"required"` +} diff --git a/entities/response/response.go b/entities/response/response.go new file mode 100644 index 000000000..10113f132 --- /dev/null +++ b/entities/response/response.go @@ -0,0 +1,23 @@ +package response + +type Response struct { + Status bool `json:"status"` + Message string `json:"message"` + Data interface{} `json:"data"` +} + +func (r *Response) Error(err error) Response { + r.Status = false + r.Message = err.Error() + r.Data = nil + + return *r +} + +func (r *Response) Success(data interface{}) Response { + r.Status = true + r.Message = "Successful operation" + r.Data = data + + return *r +} diff --git a/entities/sqlite/db.go b/entities/sqlite/db.go new file mode 100644 index 000000000..cb466d731 --- /dev/null +++ b/entities/sqlite/db.go @@ -0,0 +1,65 @@ +package sqlite + +import ( + log "github.com/sirupsen/logrus" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" + _const "togo-thdung002/const" + "togo-thdung002/entities" +) + +// LiteDB for working with sqllite +type LiteDB struct { + DB *gorm.DB +} + +func NewDB(db *gorm.DB) *LiteDB { + db.AutoMigrate(&entities.Task{}) + db.AutoMigrate(&entities.User{}) + + return &LiteDB{DB: db} +} + +func (s *LiteDB) GetTaskFilterBy(userID uint, date string) (tasks []entities.Task, err error) { + err = s.DB.Where(entities.Task{UserID: userID, Date: date}).Find(&tasks).Error + return +} + +func (s *LiteDB) CreateTask(task *entities.Task) (uint, error) { + err := s.DB.Create(task).Error + if err != nil { + log.Error(err) + return 0, _const.ErrOnCreateTask + + } + return task.ID, nil +} + +func (s *LiteDB) CreateUser(user *entities.User) (uint, error) { + pHashed, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) + if err != nil { + return 0, err + } + user.Password = string(pHashed) + err = s.DB.Create(user).Error + if err != nil { + log.Error(err) + return 0, _const.ErrOnCreateUser + } + return user.ID, nil +} + +//func (s *LiteDB) ValidateUser(username, password string) (bool, error) { +// var user entities.User +// +// rs := s.DB.Where(entities.User{Username: username, Password: password}).First(&user) +// if rs.RowsAffected > 0 { +// return true, nil +// } +// return false, _const.ErrLoginFail +//} + +func (s *LiteDB) GetUser(id uint) (user entities.User, err error) { + err = s.DB.Find(&user, id).Error + return +} diff --git a/entities/task.go b/entities/task.go new file mode 100644 index 000000000..0d0ae9e0f --- /dev/null +++ b/entities/task.go @@ -0,0 +1,37 @@ +package entities + +import ( + "github.com/go-playground/validator/v10" + "gorm.io/gorm" + "time" +) + +type CommonModel struct { + ID uint `gorm:"primaryKey;autoIncrement;not null" json:"id"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"` +} + +type Task struct { + CommonModel + Content string `json:"content" validate:"required"` + UserID uint `json:"user_id" gorm:"not null" validate:"required"` + Date string `json:"date" validate:"required" gorm:"not null"` +} + +func NewValidator() *validator.Validate { + + v := validator.New() + + return v +} + +func (c *Task) Validate() error { + + v := NewValidator() + + err := v.Struct(c) + + return err +} diff --git a/entities/user.go b/entities/user.go new file mode 100644 index 000000000..bf54b9fa9 --- /dev/null +++ b/entities/user.go @@ -0,0 +1,8 @@ +package entities + +type User struct { + CommonModel + Username string `json:"username" validate:"required, lte=5,gte=10" gorm:"unique"` + Password string `json:"password"` + Limit int `json:"limit" validate:"required" gorm:"default:5"` +} diff --git a/go.mod b/go.mod new file mode 100644 index 000000000..0e5012d9f --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module togo-thdung002 + +go 1.16 + +require ( + github.com/go-playground/validator/v10 v10.11.0 // indirect + github.com/labstack/echo/v4 v4.7.2 + github.com/sirupsen/logrus v1.8.1 + github.com/stretchr/testify v1.8.0 + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d + gorm.io/driver/sqlite v1.3.5 + gorm.io/gorm v1.23.6 +) diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..66e24454c --- /dev/null +++ b/go.sum @@ -0,0 +1,94 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= +github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= +github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= +github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= +github.com/go-playground/validator/v10 v10.11.0 h1:0W+xRM511GY47Yy3bZUbJVitCNg2BOGlCyvTqsp/xIw= +github.com/go-playground/validator/v10 v10.11.0/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/labstack/echo/v4 v4.7.2 h1:Kv2/p8OaQ+M6Ex4eGimg9b9e6icoxA42JSlOR3msKtI= +github.com/labstack/echo/v4 v4.7.2/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks= +github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o= +github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0= +github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4= +github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211103235746-7861aae1554b h1:1VkfZQv42XQlA/jchYumAnv1UPo6RgF9rJFkTgZIxO4= +golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/sqlite v1.3.5 h1:VmtQcbtN13YCUy8QNpKBBYklH0LMO7yQcmFGvRIJ/ws= +gorm.io/driver/sqlite v1.3.5/go.mod h1:Sg1/pvnKtbQ7jLXxfZa+jSHvoX8hoZA8cn4xllOMTgE= +gorm.io/gorm v1.23.4/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +gorm.io/gorm v1.23.6 h1:KFLdNgri4ExFFGTRGGFWON2P1ZN28+9SJRN8voOoYe0= +gorm.io/gorm v1.23.6/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= diff --git a/main.go b/main.go new file mode 100644 index 000000000..56e840972 --- /dev/null +++ b/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "context" + "fmt" + log "github.com/sirupsen/logrus" + "gorm.io/driver/sqlite" // Sqlite driver based on GGO + "gorm.io/gorm" + "os" + "os/signal" + "togo-thdung002/config" + "togo-thdung002/controllers" +) + +func main() { + localconf, _ := config.LoadConfig("./config/config.json") + db, err := loadDatabase(localconf) + if err != nil { + panic(err) + } + svc := controllers.NewController(localconf, db) + svc.Start() + defer svc.Stop() + svc.Load() + go svc.ListenAndServe() + log.Println("\nServer started.") + sigHandler := func() { + signChan := make(chan os.Signal, 1) + signal.Notify(signChan, os.Interrupt) + sig := <-signChan + log.Println("Cleanup processes started by ", sig, " signal") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + svc.Shutdown(ctx) + os.Exit(1) + } + + sigHandler() + +} + +func loadDatabase(cfg *config.Config) (*gorm.DB, error) { + var err error + db, err := gorm.Open(sqlite.Open(cfg.API.DBAddress), &gorm.Config{}) + if err == nil { + fmt.Println("connect database successful", cfg.API.DBAddress) + return db, nil + } + return nil, err +} diff --git a/togo.db b/togo.db new file mode 100644 index 000000000..5060d4a3b Binary files /dev/null and b/togo.db differ diff --git a/utils/utils.go b/utils/utils.go new file mode 100644 index 000000000..5ae5620c9 --- /dev/null +++ b/utils/utils.go @@ -0,0 +1,8 @@ +package utils + +import "time" + +func IsDateValue(stringDate string) bool { + _, err := time.Parse("02-01-2006", stringDate) + return err == nil +}