|
|
package main |
|
|
|
|
|
import ( |
|
|
"embed" |
|
|
"github.com/gin-contrib/sessions" |
|
|
"github.com/gin-contrib/sessions/cookie" |
|
|
"github.com/gin-gonic/gin" |
|
|
"one-api/common" |
|
|
"one-api/controller" |
|
|
"one-api/middleware" |
|
|
"one-api/model" |
|
|
"one-api/router" |
|
|
"os" |
|
|
"strconv" |
|
|
) |
|
|
|
|
|
|
|
|
var buildFS embed.FS |
|
|
|
|
|
|
|
|
var indexPage []byte |
|
|
|
|
|
func main() { |
|
|
common.SetupGinLog() |
|
|
common.SysLog("One API " + common.Version + " started") |
|
|
if os.Getenv("GIN_MODE") != "debug" { |
|
|
gin.SetMode(gin.ReleaseMode) |
|
|
} |
|
|
if common.DebugEnabled { |
|
|
common.SysLog("running in debug mode") |
|
|
} |
|
|
|
|
|
err := model.InitDB() |
|
|
if err != nil { |
|
|
common.FatalLog("failed to initialize database: " + err.Error()) |
|
|
} |
|
|
defer func() { |
|
|
err := model.CloseDB() |
|
|
if err != nil { |
|
|
common.FatalLog("failed to close database: " + err.Error()) |
|
|
} |
|
|
}() |
|
|
|
|
|
|
|
|
err = common.InitRedisClient() |
|
|
if err != nil { |
|
|
common.FatalLog("failed to initialize Redis: " + err.Error()) |
|
|
} |
|
|
|
|
|
|
|
|
model.InitOptionMap() |
|
|
if common.RedisEnabled { |
|
|
model.InitChannelCache() |
|
|
} |
|
|
if os.Getenv("SYNC_FREQUENCY") != "" { |
|
|
frequency, err := strconv.Atoi(os.Getenv("SYNC_FREQUENCY")) |
|
|
if err != nil { |
|
|
common.FatalLog("failed to parse SYNC_FREQUENCY: " + err.Error()) |
|
|
} |
|
|
common.SyncFrequency = frequency |
|
|
go model.SyncOptions(frequency) |
|
|
if common.RedisEnabled { |
|
|
go model.SyncChannelCache(frequency) |
|
|
} |
|
|
} |
|
|
if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" { |
|
|
frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY")) |
|
|
if err != nil { |
|
|
common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error()) |
|
|
} |
|
|
go controller.AutomaticallyUpdateChannels(frequency) |
|
|
} |
|
|
if os.Getenv("CHANNEL_TEST_FREQUENCY") != "" { |
|
|
frequency, err := strconv.Atoi(os.Getenv("CHANNEL_TEST_FREQUENCY")) |
|
|
if err != nil { |
|
|
common.FatalLog("failed to parse CHANNEL_TEST_FREQUENCY: " + err.Error()) |
|
|
} |
|
|
go controller.AutomaticallyTestChannels(frequency) |
|
|
} |
|
|
controller.InitTokenEncoders() |
|
|
|
|
|
|
|
|
server := gin.Default() |
|
|
|
|
|
|
|
|
server.Use(middleware.CORS()) |
|
|
|
|
|
|
|
|
store := cookie.NewStore([]byte(common.SessionSecret)) |
|
|
server.Use(sessions.Sessions("session", store)) |
|
|
|
|
|
router.SetRouter(server, buildFS, indexPage) |
|
|
var port = os.Getenv("PORT") |
|
|
if port == "" { |
|
|
port = strconv.Itoa(*common.Port) |
|
|
} |
|
|
err = server.Run(":" + port) |
|
|
if err != nil { |
|
|
common.FatalLog("failed to start HTTP server: " + err.Error()) |
|
|
} |
|
|
} |
|
|
|