-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.go
More file actions
67 lines (58 loc) · 1.36 KB
/
main.go
File metadata and controls
67 lines (58 loc) · 1.36 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
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"context"
"flag"
"gin-learning/models"
"gin-learning/routers"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
var env string
flag.StringVar(&env, "env", "develop", "Input app environment develop/testing/product")
flag.Parse()
if env != "develop" && env != "testing" && env != "product" {
os.Exit(1)
}
gin.SetMode(gin.ReleaseMode)
// 注册路由
r := routers.Register()
// 建立连接池
CreatePool(env)
srv := &http.Server{
Addr: ":8080",
Handler: r,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 优雅重启
quit := make(chan os.Signal, 1)
// kill (no param) default send syscanll.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
// catching ctx.Done(). timeout of 5 seconds.
<-ctx.Done()
log.Println("timeout of 5 seconds.")
log.Println("Server exiting")
}
func CreatePool(env string) {
models.Env = env
models.ConnectDB()
models.ConnectRedis()
}