go-cook/cmd/main.go

69 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
"database/sql"
"log"
"net/http"
v1 "git.jamestombleson.com/jtom38/go-cook/internal/handlers/v1"
"git.jamestombleson.com/jtom38/go-cook/internal/services"
2024-04-05 17:53:28 -07:00
_ "github.com/glebarez/go-sqlite"
"github.com/go-playground/validator"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
2024-04-05 17:53:28 -07:00
"github.com/pressly/goose/v3"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
func main() {
db, err := sql.Open("sqlite", "gocook.db")
if err != nil {
log.Fatal(err)
}
2024-03-31 17:47:09 -07:00
cfg := services.NewEnvConfig()
2024-04-05 17:53:28 -07:00
// Check if we should apply migrations on startup
// You can disable this in the ENV configuration of your application.
if !cfg.DisableMigrationsOnStartUp {
err = goose.SetDialect("sqlite3")
if err != nil {
panic(err)
}
err = goose.Up(db, "../internal/migrations")
2024-04-05 17:53:28 -07:00
if err != nil {
panic(err)
}
}
e := echo.New()
e.Validator = &CustomValidator{
validator: validator.New(),
}
e.Pre(middleware.RemoveTrailingSlash())
e.Pre(middleware.Logger())
2024-03-26 17:49:01 -07:00
e.Pre(middleware.Recover())
v1Group := e.Group("/api/v1")
2024-03-31 17:47:09 -07:00
v1Api := v1.NewHandler(db, cfg)
v1Api.Register(v1Group)
e.Logger.Fatal(e.Start(":1323"))
}
type CustomValidator struct {
validator *validator.Validate
}
func (cv *CustomValidator) Validate(i interface{}) error {
if err := cv.validator.Struct(i); err != nil {
2024-04-05 17:53:28 -07:00
// Optionally, you could return the error to give each route more control over the status code
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return nil
2024-04-05 17:53:28 -07:00
}