package router import ( "embed" "net/http" "strings" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/controller" "github.com/QuantumNous/new-api/middleware" "github.com/gin-contrib/gzip" "github.com/gin-contrib/static" "github.com/gin-gonic/gin" ) // ThemeAssets holds the embedded frontend assets for both themes and // the image-gen sub-app. type ThemeAssets struct { DefaultBuildFS embed.FS DefaultIndexPage []byte ClassicBuildFS embed.FS ClassicIndexPage []byte // ImageGen is the image-generation sub-app, served at /image-gen/. // It shares the same origin as the rest of new-api so /api/* and /v1/* // are reachable via the new-api session cookie (no CORS, no sk-key). ImageGenBuildFS embed.FS ImageGenIndexPage []byte } func SetWebRouter(router *gin.Engine, assets ThemeAssets) { defaultFS := common.EmbedFolder(assets.DefaultBuildFS, "web/default/dist") classicFS := common.EmbedFolder(assets.ClassicBuildFS, "web/classic/dist") themeFS := common.NewThemeAwareFS(defaultFS, classicFS) // image-gen sub-app: serve static files under /image-gen, fall back to // its index.html for unknown sub-paths (SPA). imageGenFS := common.EmbedFolder(assets.ImageGenBuildFS, "web/image-gen/dist") router.Use(gzip.Gzip(gzip.DefaultCompression)) router.Use(middleware.GlobalWebRateLimit()) router.Use(middleware.Cache()) router.Use(static.Serve("/image-gen", imageGenFS)) router.Use(static.Serve("/", themeFS)) router.NoRoute(func(c *gin.Context) { c.Set(middleware.RouteTagKey, "web") uri := c.Request.RequestURI // API/relay/static paths are handled by their own routers — 404 cleanly. if strings.HasPrefix(uri, "/v1") || strings.HasPrefix(uri, "/api") || strings.HasPrefix(uri, "/assets") { controller.RelayNotFound(c) return } c.Header("Cache-Control", "no-cache") switch { case strings.HasPrefix(uri, "/image-gen"): // SPA fallback for the image-gen sub-app: any sub-path that didn't // hit a static file gets the image-gen index.html. c.Data(http.StatusOK, "text/html; charset=utf-8", assets.ImageGenIndexPage) case common.GetTheme() == "classic": c.Data(http.StatusOK, "text/html; charset=utf-8", assets.ClassicIndexPage) default: c.Data(http.StatusOK, "text/html; charset=utf-8", assets.DefaultIndexPage) } }) }