package utils import ( "embed" "fmt" "github.com/goccy/go-json" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/earlydata" "github.com/gofiber/fiber/v2/middleware/etag" "github.com/gofiber/fiber/v2/middleware/filesystem" "github.com/gofiber/fiber/v2/middleware/healthcheck" "github.com/gofiber/fiber/v2/middleware/helmet" "github.com/gofiber/fiber/v2/middleware/idempotency" "github.com/gofiber/fiber/v2/middleware/limiter" "github.com/gofiber/template/html/v2" "github.com/spf13/viper" "io/fs" "log" "net/http" "time" ) var DistFiles embed.FS var distFS *fs.FS func Webserver() { var engine *html.Engine if !viper.GetBool("dev") { subFS, err := fs.Sub(DistFiles, "dist") if err != nil { log.Fatalln(err) } distFS = &subFS engine = html.NewFileSystem(http.FS(*distFS), ".html") } else { engine = html.New("./dist", ".html") } if viper.GetBool("dev") { engine.Reload(true) } engine.AddFunc("viteAsset", ViteAsset) webConfig := fiber.Config{ AppName: "shadow", EnableIPValidation: true, Views: engine, ViewsLayout: "index", JSONEncoder: json.Marshal, JSONDecoder: json.Unmarshal, } if !viper.GetBool("dev") { webConfig.Prefork = true } app := fiber.New(webConfig) app.Use(earlydata.New()) app.Use(healthcheck.New()) app.Use(helmet.New()) app.Use(etag.New()) app.Use(idempotency.New()) app.Use(limiter.New(limiter.Config{ Max: 175, Expiration: 1 * time.Minute, KeyGenerator: func(c *fiber.Ctx) string { return c.Get("x-forwarded-for") }, LimiterMiddleware: limiter.SlidingWindow{}, })) if !viper.GetBool("dev") { app.Use("/assets", filesystem.New(filesystem.Config{ Root: http.FS(*distFS), PathPrefix: "assets", })) } else { app.Static("/assets", "./dist/assets") } app.Get("/", func(ctx *fiber.Ctx) error { return ctx.Render("views/index", fiber.Map{}) }) log.Fatal(app.Listen(fmt.Sprintf("%s:%d", viper.GetString("server.host"), viper.GetInt32("server.port")))) }