-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathgin.go
More file actions
54 lines (44 loc) · 1.39 KB
/
gin.go
File metadata and controls
54 lines (44 loc) · 1.39 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
package api
import (
"time"
"paperdebugger/internal/api/auth"
"paperdebugger/internal/libs/cfg"
"paperdebugger/internal/libs/logger"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
type GinServer struct {
*gin.Engine
cfg *cfg.Cfg
}
func NewGinServer(cfg *cfg.Cfg, oauthHandler *auth.OAuthHandler) *GinServer {
gin.SetMode(gin.ReleaseMode)
ginServer := &GinServer{Engine: gin.New(), cfg: cfg}
ginServer.Use(ginServer.ginLogMiddleware(), gin.Recovery())
ginServer.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
ExposeHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
// This is a general oauth2 endpoint, not related to any specific provider.
oauthRouter := ginServer.Group("/oauth2")
oauthRouter.GET("/", oauthHandler.OAuthPage)
oauthRouter.GET("/callback", oauthHandler.OAuthCallback)
oauthRouter.GET("/status", oauthHandler.OAuthStatus)
return ginServer
}
func (s *GinServer) ginLogMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
c.Next()
endTime := time.Now()
method := c.Request.Method
code := c.Writer.Status()
duration := endTime.Sub(startTime)
uri := c.Request.RequestURI
logger.GetLogger().Infof("%5s %5d %13v - %s", method, code, duration, uri)
}
}