main.go 4.0 KB

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