main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "speechAnalysis/conf"
  8. "speechAnalysis/constvar"
  9. "speechAnalysis/models"
  10. "speechAnalysis/pkg/logx"
  11. "speechAnalysis/router"
  12. "speechAnalysis/service"
  13. "syscall"
  14. "time"
  15. )
  16. func main() {
  17. // 读取配置
  18. if err := conf.Init(); err != nil {
  19. logx.Errorf("config init error! ", err.Error())
  20. return
  21. }
  22. // 日志初始化
  23. logx.Init(*conf.LogConf)
  24. defer logx.Sync()
  25. // 数据库初始化
  26. if err := models.Init(); err != nil {
  27. logx.Errorf("db init error! ", err.Error())
  28. return
  29. }
  30. //监控预加载音频文件
  31. cxt, cancel := context.WithCancel(context.Background())
  32. defer cancel()
  33. go service.PreLoad(cxt)
  34. logx.Infof("server start serve...")
  35. server := &http.Server{
  36. Addr: ":" + conf.WebConf.Port,
  37. Handler: router.NewRouter(),
  38. ReadTimeout: 5 * time.Second,
  39. WriteTimeout: 5 * time.Second,
  40. }
  41. go shutdown(server)
  42. logx.Error(server.ListenAndServe().Error())
  43. }
  44. func shutdown(server *http.Server) {
  45. quit := make(chan os.Signal, 1)
  46. signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
  47. <-quit
  48. if constvar.GrpcClient != nil {
  49. _ = constvar.GrpcClient.Close()
  50. }
  51. // 创建一个上下文,设置超时时间
  52. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  53. defer cancel()
  54. logx.Infof("server exiting...")
  55. if err := server.Shutdown(ctx); err != nil {
  56. logx.Warnf("服务优雅退出失败: %v", err)
  57. return
  58. }
  59. logx.Infof("server exited success")
  60. }