shadow/utils/server.go

66 lines
1.5 KiB
Go

package utils
import (
"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/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"
"log"
"time"
)
func Webserver() {
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{},
}))
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"))))
}