main.go 3.7 KB

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