go-cook/cmd/main.go

69 lines
1.5 KiB
Go

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"
_ "github.com/glebarez/go-sqlite"
"github.com/go-playground/validator"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"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)
}
cfg := services.NewEnvConfig()
// 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")
if err != nil {
panic(err)
}
}
e := echo.New()
e.Validator = &CustomValidator{
validator: validator.New(),
}
e.Pre(middleware.RemoveTrailingSlash())
e.Pre(middleware.Logger())
e.Pre(middleware.Recover())
v1Group := e.Group("/api/v1")
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 {
// 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
}