main.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 options
  52. model.InitOptionMap()
  53. if common.RedisEnabled {
  54. // for compatibility with old versions
  55. common.MemoryCacheEnabled = true
  56. }
  57. if common.MemoryCacheEnabled {
  58. common.SysLog("memory cache enabled")
  59. common.SysError(fmt.Sprintf("sync frequency: %d seconds", common.SyncFrequency))
  60. model.InitChannelCache()
  61. }
  62. if common.RedisEnabled {
  63. go model.SyncTokenCache(common.SyncFrequency)
  64. }
  65. if common.MemoryCacheEnabled {
  66. go model.SyncOptions(common.SyncFrequency)
  67. go model.SyncChannelCache(common.SyncFrequency)
  68. }
  69. // 数据看板
  70. go model.UpdateQuotaData()
  71. if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
  72. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY"))
  73. if err != nil {
  74. common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error())
  75. }
  76. go controller.AutomaticallyUpdateChannels(frequency)
  77. }
  78. if os.Getenv("CHANNEL_TEST_FREQUENCY") != "" {
  79. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_TEST_FREQUENCY"))
  80. if err != nil {
  81. common.FatalLog("failed to parse CHANNEL_TEST_FREQUENCY: " + err.Error())
  82. }
  83. go controller.AutomaticallyTestChannels(frequency)
  84. }
  85. if common.IsMasterNode && constant.UpdateTask {
  86. gopool.Go(func() {
  87. controller.UpdateMidjourneyTaskBulk()
  88. })
  89. gopool.Go(func() {
  90. controller.UpdateTaskBulk()
  91. })
  92. }
  93. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  94. common.BatchUpdateEnabled = true
  95. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  96. model.InitBatchUpdater()
  97. }
  98. if os.Getenv("ENABLE_PPROF") == "true" {
  99. go func() {
  100. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  101. }()
  102. go common.Monitor()
  103. common.SysLog("pprof enabled")
  104. }
  105. service.InitTokenEncoders()
  106. // Initialize HTTP server
  107. server := gin.New()
  108. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  109. common.SysError(fmt.Sprintf("panic detected: %v", err))
  110. c.JSON(http.StatusInternalServerError, gin.H{
  111. "error": gin.H{
  112. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  113. "type": "new_api_panic",
  114. },
  115. })
  116. }))
  117. // This will cause SSE not to work!!!
  118. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  119. server.Use(middleware.RequestId())
  120. middleware.SetUpLogger(server)
  121. // Initialize session store
  122. store := cookie.NewStore([]byte(common.SessionSecret))
  123. server.Use(sessions.Sessions("session", store))
  124. router.SetRouter(server, buildFS, indexPage)
  125. var port = os.Getenv("PORT")
  126. if port == "" {
  127. port = strconv.Itoa(*common.Port)
  128. }
  129. err = server.Run(":" + port)
  130. if err != nil {
  131. common.FatalLog("failed to start HTTP server: " + err.Error())
  132. }
  133. }