manager/cmd/ui.go

106 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-04-08 16:12:35 +02:00
package cmd
import (
2022-04-08 23:02:14 +02:00
"errors"
2022-04-08 16:12:35 +02:00
"fmt"
2022-04-08 23:02:14 +02:00
"io/fs"
"os"
"strings"
2023-11-12 17:33:36 +01:00
"code.icod.de/dalu/ginpongo2/v6"
2022-05-22 14:56:45 +02:00
"code.icod.de/postfix/manager/ent"
2022-04-08 23:02:14 +02:00
"code.icod.de/postfix/manager/ui"
2022-05-22 14:56:45 +02:00
"code.icod.de/postfix/manager/ui/handler"
2023-11-12 17:33:36 +01:00
"github.com/flosch/pongo2/v6"
2022-04-08 23:02:14 +02:00
"github.com/gin-gonic/gin"
2022-04-08 16:12:35 +02:00
"github.com/spf13/cobra"
)
2022-04-08 23:02:14 +02:00
const (
prefixTCP = "tcp:"
prefixUNIX = "unix:"
)
var (
uiDebug bool
uiAddr string
)
2022-04-08 16:12:35 +02:00
// uiCmd represents the ui command
var uiCmd = &cobra.Command{
Use: "ui",
Short: "serves the management ui over http",
2022-04-08 23:02:14 +02:00
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
}
2022-05-22 14:56:45 +02:00
// Database
client, e := ent.Open("mysql", "dev:dev@tcp(localhost:3306)/postfix")
if e != nil {
return e
}
defer client.Close()
handler.SetClient(client)
2022-04-08 23:02:14 +02:00
// Static
r.Static("/assets/", "./assets/")
2022-05-22 14:56:45 +02:00
r.GET("/", handler.GETIndex)
2022-04-08 23:02:14 +02:00
// serve
if strings.HasPrefix(uiAddr, prefixTCP) {
addr := strings.TrimPrefix(uiAddr, prefixTCP)
2023-11-12 17:33:36 +01:00
fmt.Println("listening on", fmt.Sprintf("http://%s", addr))
2022-04-08 23:02:14 +02:00
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 {
2023-11-12 17:33:36 +01:00
fmt.Println("listening on ", addr)
2022-04-08 23:02:14 +02:00
return r.RunUnix(addr)
}
}
} else {
return nil
}
2022-04-08 16:12:35 +02:00
},
}
func init() {
rootCmd.AddCommand(uiCmd)
2022-04-08 23:02:14 +02:00
uiCmd.Flags().BoolVar(&uiDebug, "debug", false, "enable dev mode")
uiCmd.Flags().StringVar(
&uiAddr,
"addr",
"tcp:localhost:8080",
"either tcp: or unix: e.g. tcp:localhost:3030 unix:/tmp/listen.sock",
)
2022-04-08 16:12:35 +02:00
}