forked from eddycjy/go-gin-example
/
main.go
executable file
·97 lines (91 loc) · 2.73 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"github.com/Quons/go-gin-example/common"
"github.com/Quons/go-gin-example/models"
"github.com/Quons/go-gin-example/pkg/gredis"
"github.com/Quons/go-gin-example/pkg/logging"
"github.com/Quons/go-gin-example/pkg/setting"
"github.com/Quons/go-gin-example/routers"
"github.com/gin-contrib/cors"
"github.com/sirupsen/logrus"
"log"
"net/http"
"os"
"os/signal"
"runtime"
"time"
)
func init() {
var runmode string
flag.StringVar(&runmode, "runmode", "dev", "runmode:dev,test,pre,prod;default dev mode")
flag.Parse()
setting.Setup(runmode)
logging.Setup()
models.Setup()
gredis.Setup()
}
// @title Golang Gin API
// @version 1.0
// @description An example of gin
// @termsOfService https://github.com/Quons/go-gin-example
// @license.name MIOd
// @license.url https://github.com/Quons/go-gin-example/blob/master/LICENSE
func main() {
common.TestFunc()
routersInit := routers.InitRouter()
//跨域请求设置
corsConfig := cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Origin", "Authorization", "Accept", "DNT", "Referer", "User-Agent", "Access-Control-Request-Method", "Access-Control-Allow-Headers", "Content-Type"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Headers", "Content-Type"},
AllowCredentials: true,
}
routersInit.Use(cors.New(corsConfig))
readTimeout := setting.ServerSetting.ReadTimeout
writeTimeout := setting.ServerSetting.WriteTimeout
endPoint := fmt.Sprintf(":%d", setting.ServerSetting.HttpPort)
maxHeaderBytes := 1 << 20
if runtime.GOOS == "windows" {
server := &http.Server{
Addr: endPoint,
Handler: routersInit,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: maxHeaderBytes,
}
server.ListenAndServe()
return
}
//服务器设置
srv := &http.Server{
Addr: endPoint,
Handler: routersInit,
ErrorLog: log.New(logging.GetLogrusWriter(), "server err:", log.LstdFlags),
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: maxHeaderBytes,
}
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Fatalf("listen: %s\n", err)
}
}()
logrus.Info("server started")
//平滑重启设置 福
//Wait for interrupt signal to gracefully shutdown the server with a timeout of 5 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
logrus.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logrus.Fatal("Server Shutdown:", err)
}
logrus.Println("Server exiting")
}