main.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. common.SafeGoroutine(func() {
  84. controller.UpdateMidjourneyTaskBulk()
  85. })
  86. common.SafeGoroutine(func() {
  87. controller.UpdateTaskBulk()
  88. })
  89. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  90. common.BatchUpdateEnabled = true
  91. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  92. model.InitBatchUpdater()
  93. }
  94. if os.Getenv("ENABLE_PPROF") == "true" {
  95. go func() {
  96. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  97. }()
  98. go common.Monitor()
  99. common.SysLog("pprof enabled")
  100. }
  101. service.InitTokenEncoders()
  102. // Initialize HTTP server
  103. server := gin.New()
  104. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  105. common.SysError(fmt.Sprintf("panic detected: %v", err))
  106. c.JSON(http.StatusInternalServerError, gin.H{
  107. "error": gin.H{
  108. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  109. "type": "new_api_panic",
  110. },
  111. })
  112. }))
  113. // This will cause SSE not to work!!!
  114. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  115. server.Use(middleware.RequestId())
  116. middleware.SetUpLogger(server)
  117. // Initialize session store
  118. store := cookie.NewStore([]byte(common.SessionSecret))
  119. server.Use(sessions.Sessions("session", store))
  120. router.SetRouter(server, buildFS, indexPage)
  121. var port = os.Getenv("PORT")
  122. if port == "" {
  123. port = strconv.Itoa(*common.Port)
  124. }
  125. err = server.Run(":" + port)
  126. if err != nil {
  127. common.FatalLog("failed to start HTTP server: " + err.Error())
  128. }
  129. }