-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
68 lines (59 loc) · 1.59 KB
/
server.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
package server
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-playground/validator"
"github.com/labstack/echo/middleware"
"github.com/Pradnyana28/go-rest-api-boilerplate/pkg/utl/middleware/secure"
"github.com/labstack/echo"
)
// New instantates new Echo server
func New() *echo.Echo {
e := echo.New()
e.Use(middleware.Logger(), middleware.Recover(),
secure.CORS(), secure.Headers())
e.GET("/", healthCheck)
e.Validator = &CustomValidator{V: validator.New()}
custErr := &customErrHandler{e: e}
e.HTTPErrorHandler = custErr.handler
e.Binder = &CustomBinder{b: &echo.DefaultBinder{}}
return e
}
func healthCheck(c echo.Context) error {
return c.JSON(http.StatusOK, "OK")
}
// Config represents server specific config
type Config struct {
Port string
ReadTimeoutSeconds int
WriteTimeoutSeconds int
Debug bool
}
// Start starts echo server
func Start(e *echo.Echo, cfg *Config) {
s := &http.Server{
Addr: cfg.Port,
ReadTimeout: time.Duration(cfg.ReadTimeoutSeconds) * time.Second,
WriteTimeout: time.Duration(cfg.WriteTimeoutSeconds) * time.Second,
}
e.Debug = cfg.Debug
// Start server
go func() {
if err := e.StartServer(s); err != nil {
e.Logger.Info("Shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 10 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}