main.go 3.8 KB

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