shadow/cmd/run.go

94 lines
2.2 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/template/html/v2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"log"
"os"
"strings"
)
func viteAsset(src string) string {
file, err := os.ReadFile("dist/.vite/manifest.json")
if err != nil {
log.Fatalln(err)
}
var viteManifestData map[string]map[string]interface{}
if err := json.Unmarshal(file, &viteManifestData); err != nil {
log.Fatalln(err)
}
src = strings.TrimPrefix(src, "/")
if _, ok := viteManifestData[src]; ok {
return "/" + viteManifestData[src]["file"].(string)
} else {
return ""
}
}
// 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") {
go utils.RunViteServer()
}
engine := html.New("./dist", ".html")
if viper.GetBool("dev") {
engine.Reload(true)
}
engine.AddFunc("viteAsset", viteAsset)
app := fiber.New(fiber.Config{
AppName: "shadow",
EnableIPValidation: true,
Views: engine,
ViewsLayout: "index",
})
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")
}