run.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package lxrun
  2. import (
  3. "context"
  4. "fmt"
  5. "git.listensoft.net/tool/lxutils/lxDb"
  6. "git.listensoft.net/tool/lxutils/lxLock"
  7. "git.listensoft.net/tool/lxutils/lxlog"
  8. "git.listensoft.net/tool/lxutils/lxzap"
  9. "github.com/gin-gonic/gin"
  10. "log"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "syscall"
  15. "time"
  16. )
  17. func Run(env string, port string, fun func(), r func(router *gin.Engine), zapConfig lxzap.ZapLogConfig, dbConf []lxDb.DbConfig, redisConf lxDb.RedisConfig) {
  18. _ = lxlog.InitLog()
  19. err := lxzap.InitZapLogger(zapConfig, env)
  20. if err != nil {
  21. panic(err.Error())
  22. }
  23. app := gin.New()
  24. // 注册zap相关中间件
  25. if env == "dev" {
  26. app.Use(gin.Logger(), gin.Recovery())
  27. } else {
  28. app.Use(lxzap.GinLogger(), lxzap.GinRecovery(true))
  29. }
  30. lxDb.InitDBS(env, dbConf)
  31. lxDb.InitRedis(redisConf)
  32. lxLock.InitRedis(redisConf)
  33. fun()
  34. r(app)
  35. srv := http.Server{
  36. Addr: ":" + port,
  37. Handler: app,
  38. }
  39. // make sure idle connections returned
  40. processed := make(chan struct{})
  41. go func() {
  42. c := make(chan os.Signal, 1)
  43. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  44. <-c
  45. fmt.Println("ctrl + c")
  46. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  47. defer cancel()
  48. if err := srv.Shutdown(ctx); nil != err {
  49. log.Fatalf("server shutdown failed, err: %v\n", err)
  50. }
  51. log.Println("server gracefully shutdown")
  52. processed <- struct{}{}
  53. }()
  54. // serve
  55. err = srv.ListenAndServe()
  56. if http.ErrServerClosed != err {
  57. log.Fatalf("server not gracefully shutdown, err :%v\n", err)
  58. }
  59. // waiting for goroutine above processed
  60. <-processed
  61. }