main.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "github.com/gin-contrib/sessions"
  6. "github.com/gin-contrib/sessions/cookie"
  7. "github.com/gin-gonic/gin"
  8. "log"
  9. "net/http"
  10. "one-api/common"
  11. "one-api/constant"
  12. "one-api/controller"
  13. "one-api/middleware"
  14. "one-api/model"
  15. "one-api/router"
  16. "one-api/service"
  17. "os"
  18. "strconv"
  19. _ "net/http/pprof"
  20. )
  21. //go:embed web/dist
  22. var buildFS embed.FS
  23. //go:embed web/dist/index.html
  24. var indexPage []byte
  25. func main() {
  26. common.SetupLogger()
  27. common.SysLog("New API " + common.Version + " started")
  28. if os.Getenv("GIN_MODE") != "debug" {
  29. gin.SetMode(gin.ReleaseMode)
  30. }
  31. if common.DebugEnabled {
  32. common.SysLog("running in debug mode")
  33. }
  34. // Initialize SQL Database
  35. err := model.InitDB()
  36. if err != nil {
  37. common.FatalLog("failed to initialize database: " + err.Error())
  38. }
  39. defer func() {
  40. err := model.CloseDB()
  41. if err != nil {
  42. common.FatalLog("failed to close database: " + err.Error())
  43. }
  44. }()
  45. // Initialize Redis
  46. err = common.InitRedisClient()
  47. if err != nil {
  48. common.FatalLog("failed to initialize Redis: " + err.Error())
  49. }
  50. // Initialize options
  51. model.InitOptionMap()
  52. if common.RedisEnabled {
  53. // for compatibility with old versions
  54. common.MemoryCacheEnabled = true
  55. }
  56. if common.MemoryCacheEnabled {
  57. common.SysLog("memory cache enabled")
  58. common.SysError(fmt.Sprintf("sync frequency: %d seconds", common.SyncFrequency))
  59. model.InitChannelCache()
  60. }
  61. if common.RedisEnabled {
  62. go model.SyncTokenCache(common.SyncFrequency)
  63. }
  64. if common.MemoryCacheEnabled {
  65. go model.SyncOptions(common.SyncFrequency)
  66. go model.SyncChannelCache(common.SyncFrequency)
  67. }
  68. // 数据看板
  69. go model.UpdateQuotaData()
  70. if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
  71. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY"))
  72. if err != nil {
  73. common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error())
  74. }
  75. go controller.AutomaticallyUpdateChannels(frequency)
  76. }
  77. if os.Getenv("CHANNEL_TEST_FREQUENCY") != "" {
  78. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_TEST_FREQUENCY"))
  79. if err != nil {
  80. common.FatalLog("failed to parse CHANNEL_TEST_FREQUENCY: " + err.Error())
  81. }
  82. go controller.AutomaticallyTestChannels(frequency)
  83. }
  84. if common.IsMasterNode && constant.UpdateTask {
  85. common.SafeGoroutine(func() {
  86. controller.UpdateMidjourneyTaskBulk()
  87. })
  88. common.SafeGoroutine(func() {
  89. controller.UpdateTaskBulk()
  90. })
  91. }
  92. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  93. common.BatchUpdateEnabled = true
  94. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  95. model.InitBatchUpdater()
  96. }
  97. if os.Getenv("ENABLE_PPROF") == "true" {
  98. go func() {
  99. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  100. }()
  101. go common.Monitor()
  102. common.SysLog("pprof enabled")
  103. }
  104. service.InitTokenEncoders()
  105. // Initialize HTTP server
  106. server := gin.New()
  107. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  108. common.SysError(fmt.Sprintf("panic detected: %v", err))
  109. c.JSON(http.StatusInternalServerError, gin.H{
  110. "error": gin.H{
  111. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  112. "type": "new_api_panic",
  113. },
  114. })
  115. }))
  116. // This will cause SSE not to work!!!
  117. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  118. server.Use(middleware.RequestId())
  119. middleware.SetUpLogger(server)
  120. // Initialize session store
  121. store := cookie.NewStore([]byte(common.SessionSecret))
  122. server.Use(sessions.Sessions("session", store))
  123. router.SetRouter(server, buildFS, indexPage)
  124. var port = os.Getenv("PORT")
  125. if port == "" {
  126. port = strconv.Itoa(*common.Port)
  127. }
  128. err = server.Run(":" + port)
  129. if err != nil {
  130. common.FatalLog("failed to start HTTP server: " + err.Error())
  131. }
  132. }