-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
85 lines (73 loc) · 1.92 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package server
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"time"
"producer/internal/middleware/secure"
"github.com/go-playground/validator"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
// New instantates new Echo server
func New() *echo.Echo {
e := echo.New()
e.Use(middleware.Logger(), middleware.Recover(), secure.CORS(), secure.Headers())
e.GET("/producer-svc", healthCheck)
e.GET("/producer-svc/ping-what", sayPong)
e.Validator = &CustomValidator{V: validator.New()}
custErr := &customErrHandler{e: e}
e.HTTPErrorHandler = custErr.handler
e.Binder = &CustomBinder{b: &echo.DefaultBinder{}}
return e
}
type response struct {
Data string `json:"data"`
}
func healthCheck(c echo.Context) error {
return c.JSON(http.StatusOK, response{Data: "producer: Go template at your service!🍲"})
}
type PongResponse struct {
Ok string `json:"ok"`
}
func sayPong(ctx echo.Context) error {
u := &PongResponse{
Ok: "Pong!",
}
return ctx.JSON(http.StatusOK, u)
}
// 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() {
fmt.Print("Warming up server... ")
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, 1)
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.StdLogger.Fatal(err)
}
}