-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.go
102 lines (82 loc) · 2.37 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
/**
* @file
* @copyright defined in scan-api/LICENSE
*/
package server
import (
"fmt"
"net/http"
"time"
"github.com/seeleteam/scan-api/api/routers"
"github.com/seeleteam/scan-api/database"
"github.com/seeleteam/scan-api/log"
limit "github.com/aviddiviner/gin-limit"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
//ScanServer hold instance of server
type ScanServer struct {
Server *http.Server
G *errgroup.Group
config *Config
r *routers.Router
}
//initGin init gin engine
func initGin(config *Config) *gin.Engine {
gin.SetMode(config.GinMode)
if config.DisableConsoleColor {
gin.DisableConsoleColor()
}
e := gin.New()
// use logs middleware
e.Use(log.Logger(log.GetLogger()))
e.Use(gin.Recovery())
corsConfig := cors.Config{
AllowMethods: []string{"GET", "POST", "PUT", "HEAD", "OPTIONS"},
//AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "x-fc-version", "x-fc-terminal", "*"},
AllowHeaders: []string{"*"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}
corsConfig.AllowAllOrigins = true
e.Use(cors.New(corsConfig))
// By default, http.ListenAndServe (which gin.Run wraps) will serve an unbounded number of requests.
// Limiting the number of simultaneous connections can sometimes greatly speed things up under load
if config.LimitConnections > 0 {
e.Use(limit.MaxAllowed(config.LimitConnections))
}
return e
}
//GetServer init scanServer and return server instance
func GetServer(g *errgroup.Group, config *Config) (server *ScanServer) {
if config == nil {
log.Error("[initGin] server config is nil")
}
ginHandler := initGin(config)
dbClient := database.NewDBClient(config.DataBase, 1)
if dbClient == nil {
fmt.Printf("init database error")
return
}
router := routers.New(dbClient, dbClient, dbClient)
router.Init(ginHandler)
return &ScanServer{
Server: &http.Server{
Addr: config.Addr,
Handler: ginHandler,
ReadTimeout: config.ReadTimeout * time.Second,
WriteTimeout: config.WriteTimeout * time.Second,
IdleTimeout: config.IdleTimeout * time.Second,
MaxHeaderBytes: 1 << config.MaxHeaderBytes,
},
G: g,
r: router,
}
}
//RunServer Run our server in a goroutine
func (sl *ScanServer) RunServer() {
sl.G.Go(func() error {
return http.ListenAndServe(sl.Server.Addr, sl.Server.Handler)
})
}