htmxginpongo/cmd/serve.go
2023-10-02 17:42:50 +02:00

110 lines
2.5 KiB
Go

package cmd
import (
"code.icod.de/dalu/ginpongo2/v6"
"code.icod.de/dalu/htmxginpongo/server"
"code.icod.de/dalu/htmxginpongo/ui"
_ "code.icod.de/dalu/pongo2-addons/v6"
"errors"
"fmt"
"github.com/flosch/pongo2/v6"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"io/fs"
"os"
"strings"
)
const (
prefixTCP = "tcp:"
prefixUNIX = "unix:"
)
var (
uiDebug bool
uiAddr string
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "A brief description of your command",
RunE: func(cmd *cobra.Command, args []string) error {
if !uiDebug {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
r.SecureJsonPrefix(")]}',\n")
r.MaxMultipartMemory = 8 << 20
if uiDebug {
fmt.Println("debug mode")
fl, e := pongo2.NewLocalFileSystemLoader("ui/templates/")
if e != nil {
return e
}
hr := ginpongo2.New(true, fl)
r.HTMLRender = hr
} else {
fmt.Println("release mode")
subFS, e := fs.Sub(ui.Templates, "templates")
if e != nil {
return e
}
fl := pongo2.NewFSLoader(subFS)
hr := ginpongo2.New(false, fl)
r.HTMLRender = hr
}
// Static
r.Static("/assets", "assets")
s := server.Server{}
r.GET("/", s.GETIndex)
r.POST("/", s.POSTIndex)
// serve
if strings.HasPrefix(uiAddr, prefixTCP) {
addr := strings.TrimPrefix(uiAddr, prefixTCP)
fmt.Printf("listening on http://%s\n", addr)
return r.Run(addr)
} else if strings.HasPrefix(uiAddr, prefixUNIX) {
addr := strings.TrimPrefix(uiAddr, prefixUNIX)
if _, e := os.Stat(addr); errors.Is(e, os.ErrNotExist) {
fmt.Println("listening on", addr)
return r.RunUnix(addr)
} else {
if e := os.Remove(addr); e != nil {
return e
} else {
fmt.Println("listening on", addr)
return r.RunUnix(addr)
}
}
} else {
return nil
}
},
}
func init() {
rootCmd.AddCommand(serveCmd)
serveCmd.Flags().BoolVar(&uiDebug, "debug", false, "enable dev mode")
serveCmd.Flags().StringVar(
&uiAddr,
"addr",
"tcp:localhost:8080",
"either tcp: or unix: e.g. tcp:localhost:3030 unix:/tmp/listen.sock",
)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// serveCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}