shadow/cmd/run.go

95 lines
2.6 KiB
Go

/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"git.shadowhosting.xyz/shadow/utils"
"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/cobra"
"github.com/spf13/viper"
"log"
"time"
)
// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
if viper.GetBool("dev") && !fiber.IsChild() {
go utils.RunViteServer()
}
engine := html.New("./dist", ".html")
if viper.GetBool("dev") {
engine.Reload(true)
}
engine.AddFunc("viteAsset", utils.ViteAsset)
app := fiber.New(fiber.Config{
AppName: "shadow",
EnableIPValidation: true,
Views: engine,
ViewsLayout: "index",
Prefork: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
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"))))
},
}
func init() {
rootCmd.AddCommand(runCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// runCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// runCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}