-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
77 lines (61 loc) · 1.72 KB
/
server.go
File metadata and controls
77 lines (61 loc) · 1.72 KB
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
71
72
73
74
75
76
77
package main
import (
"bytes"
"firstApi/repository"
"firstApi/routes"
"firstApi/util"
"net/http"
"time"
"github.com/go-playground/validator"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Server struct{}
// NewServer creates a new instance of Server.
func NewServer() *Server {
return &Server{}
}
// ListenAndServe represents the main entry point of the program.
//
// Sets up DB connection logic, registers routes and listens for connections.
func (s *Server) ListenAndServe() error {
config := util.NewConfig()
e := echo.New()
e.Validator = &util.Validator{Instance: validator.New()}
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
setupMiddlewares(e)
storage, err := repository.NewStorage(config.DBName)
if err != nil {
return err
}
err = storage.Migrate()
if err != nil {
return err
}
api := e.Group("/api")
routes.SetupRoute(api, storage)
return e.Start(":" + config.Port)
}
// setupMiddlewares sets up middlewares for logging, timming and recovering.
func setupMiddlewares(e *echo.Echo) {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: `${time_rfc3339} | ${method} ${uri} | ${status} | ${custom} | ${remote_ip} | ${user_agent}` + "\n",
CustomTimeFormat: time.RFC3339,
CustomTagFunc: func(c echo.Context, buf *bytes.Buffer) (int, error) {
start := c.Get("start_time").(time.Time)
end := time.Now()
latencyStr := util.CustomLatency(start, end)
return buf.WriteString(latencyStr)
},
Output: nil,
}))
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set("start_time", time.Now())
return next(c)
}
})
e.Use(middleware.Recover())
}