-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserve.go
70 lines (67 loc) · 1.94 KB
/
serve.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cli
import (
"errors"
"github.com/enchant97/note-mark/backend/config"
"github.com/enchant97/note-mark/backend/core"
"github.com/enchant97/note-mark/backend/db"
"github.com/enchant97/note-mark/backend/routes"
"github.com/enchant97/note-mark/backend/storage"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"gorm.io/gorm"
"net/http"
)
// HTTP error handler, to handle unexpected errors
func httpErrorHandler(err error, ctx echo.Context) {
if e, ok := err.(*echo.HTTPError); ok {
// normal HTTP error
ctx.JSON(e.Code, e.Message)
return
}
ctx.Logger().Error(err)
if errors.Is(err, gorm.ErrRecordNotFound) {
ctx.NoContent(http.StatusNotFound)
} else if errors.Is(err, gorm.ErrDuplicatedKey) {
ctx.NoContent(http.StatusConflict)
} else if errors.Is(err, core.ErrBind) || errors.Is(err, core.ErrValidation) {
ctx.NoContent(http.StatusUnprocessableEntity)
} else {
ctx.NoContent(http.StatusInternalServerError)
}
}
func commandServe(appConfig config.AppConfig) error {
// Connect to storage backend
storage_backend := storage.DiskController{}.New(appConfig.DataPath)
if err := storage_backend.Setup(); err != nil {
return err
}
defer storage_backend.TearDown()
// Connect to database
if err := db.InitDB(appConfig.DB); err != nil {
return err
}
// Create server
e := echo.New()
e.HTTPErrorHandler = httpErrorHandler
// Register root middleware
e.Use(middleware.Recover())
e.Use(middleware.Logger())
corsConfig := middleware.DefaultCORSConfig
{
corsConfig.AllowOrigins = appConfig.CORSOrigins
}
e.Use(middleware.CORSWithConfig(corsConfig))
v := core.Validator{}.New()
e.Validator = &v
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
ctx.Set("AppConfig", appConfig)
ctx.Set("Storage", storage_backend)
return next(ctx)
}
})
// Init routes
routes.InitRoutes(e, appConfig)
// Start server
return e.Start(appConfig.Bind.AsAddress())
}