/
server.go
166 lines (127 loc) · 3.72 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
gjwt "github.com/alexditu/gogymapp/internal/gjwt"
"github.com/alexditu/gogymapp/internal/logging"
"github.com/alexditu/gogymapp/internal/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
)
type server struct {
router *gin.Engine
// dbConn *mongo.Client
// cfg *config.Config
ctx context.Context
setts *Settings
localTZ string
}
func Run(binaryName string, setts *Settings) error {
if setts == nil {
fmt.Printf("Error: setts is nil")
return fmt.Errorf("setts is nil")
}
if err := logging.InitStandardLogger(&setts.Log); err != nil {
fmt.Printf("Failed to init logging: %s\n", err)
return err
}
log.Infof("%s started (pid: %d)", binaryName, os.Getpid())
// catch interrupt signals
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
server, err := newServer(ctx, setts)
defer server.stop()
if err != nil {
log.Errorf("init failed: %s", err)
return err
}
server.setupRoutes()
httpSrv := server.run()
<-ctx.Done()
// restore default behavior to interrupt signals
stop()
log.Info("Shutting down gracefully, press Ctrl+C again to force")
// signal the server to graceful shutdown in max 5 seconds
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := httpSrv.Shutdown(ctx); err != nil {
log.Warnf("Server forced to shutdown: %s", err)
return err
}
log.Infof("%s finished (pid: %d)", binaryName, os.Getpid())
return nil
}
func newServer(ctx context.Context, setts *Settings) (*server, error) {
// use separate logging file for gin
ginLogger, err := logging.NewLogger(&logging.Settings{LogToFile: true, FileName: "gin.log", Level: log.DebugLevel})
if err != nil {
return nil, err
}
// ginLogger.SetFormatter(&logrus.JSONFormatter{})
router := gin.New()
router.Use(ginlogrus.Logger(ginLogger), gin.Recovery())
tz, err := utils.LocalTimeZone()
if err != nil {
log.Warnf("Failed to read timezone info: '%s'. Using UTC.", err)
tz = "UTC"
}
s := server{router: router, ctx: ctx, localTZ: tz, setts: setts}
return &s, nil
}
// server methods
func (s *server) stop() {
}
func (s *server) run() *http.Server {
w := log.StandardLogger().Writer()
// write newHttpServer in another file due to log naming conflict (logrus vs log)
srv := newHttpServer(s, w)
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
err := srv.ListenAndServeTLS(s.setts.CertPath, s.setts.KeyPath)
if err != nil && err != http.ErrServerClosed {
log.Fatalf("failed to start https server: %s", err)
}
// close the pipe that http.Server is writing to after goroutine exits
defer w.Close()
}()
return srv
}
func (s *server) setupRoutes() {
s.router.MaxMultipartMemory = 8 << 20 // 8 MiB
// need by HTML Templating engine
s.router.LoadHTMLGlob(s.setts.HtmlPath + "/*.html")
s.router.GET("/", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/dashboard")
})
s.router.Static("/static", s.setts.HtmlPath)
// REST API
api := s.router.Group("/api/v1")
{
auth := api.Group("/auth")
{
auth.POST("/loginCbk", s.loginCbk())
}
}
}
func (s *server) loginCbk() gin.HandlerFunc {
return func(c *gin.Context) {
creds := c.PostForm("credential")
csrf_token := c.PostForm("g_csrf_token")
log.Infof("loginCbk: creds: %s, csrf_token: %s", creds, csrf_token)
claims, err := gjwt.ValidateGoogleJWT(c, s.setts.ClientId)
if err != nil {
c.Status(http.StatusUnauthorized)
}
j, _ := json.Marshal(*claims)
log.Infof("claims: %s", string(j))
c.Status(http.StatusOK)
}
}