12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package lxrun
- import (
- "context"
- "fmt"
- "git.listensoft.net/tool/lxutils/lxDb"
- "git.listensoft.net/tool/lxutils/lxLock"
- "git.listensoft.net/tool/lxutils/lxlog"
- "git.listensoft.net/tool/lxutils/lxzap"
- "github.com/gin-gonic/gin"
- "log"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
- )
- func Run(env string, port string, fun func(), r func(router *gin.Engine), zapConfig lxzap.ZapLogConfig, dbConf []lxDb.DbConfig, redisConf lxDb.RedisConfig) {
- _ = lxlog.InitLog()
- err := lxzap.InitZapLogger(zapConfig, env)
- if err != nil {
- panic(err.Error())
- }
- app := gin.New()
- // 注册zap相关中间件
- if env == "dev" {
- app.Use(gin.Logger(), gin.Recovery())
- } else {
- app.Use(lxzap.GinLogger(), lxzap.GinRecovery(true))
- }
- lxDb.InitDBS(env, dbConf)
- lxDb.InitRedis(redisConf)
- lxLock.InitRedis(redisConf)
- fun()
- r(app)
- srv := http.Server{
- Addr: ":" + port,
- Handler: app,
- }
- // make sure idle connections returned
- processed := make(chan struct{})
- go func() {
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt, syscall.SIGTERM)
- <-c
- fmt.Println("ctrl + c")
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
- if err := srv.Shutdown(ctx); nil != err {
- log.Fatalf("server shutdown failed, err: %v\n", err)
- }
- log.Println("server gracefully shutdown")
- processed <- struct{}{}
- }()
- // serve
- err = srv.ListenAndServe()
- if http.ErrServerClosed != err {
- log.Fatalf("server not gracefully shutdown, err :%v\n", err)
- }
- // waiting for goroutine above processed
- <-processed
- }
|