main.go 4.0 KB

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