makeshift/cmd/serve.go

67 lines
1.8 KiB
Go

package cmd
import (
"time"
"git.towk2.me/towk/configurator/pkg/service"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var serveCmd = &cobra.Command{
Use: "serve",
Args: cobra.NoArgs,
PreRun: func(cmd *cobra.Command, args []string) {
// try and set flags using env vars
setenv(&host, "CONFIGURATOR_HOST")
setenv(&rootPath, "CONFIGURATOR_ROOT")
},
Run: func(cmd *cobra.Command, args []string) {
var (
host string
rootPath string
server *service.Service
err error
)
// get vars but don't modify
host, _ = cmd.Flags().GetString("host")
rootPath, _ = cmd.Flags().GetString("root")
// set the server values
server = service.New()
server.Addr = host
server.RootPath = rootPath
server.Timeout = time.Duration(timeout) * time.Second
// show some debugging information
log.Debug().
Str("host", host).
Any("paths", map[string]string{
"root": rootPath,
"data": server.PathForData(),
"profiles": server.PathForProfiles(),
"plugins": server.PathForPlugins(),
"metadata": server.PathForMetadata(),
}).
Send()
// make the default directories and files if flag is passed
if cmd.Flags().Changed("init") {
server.Init()
}
// serve and log why the server closed
err = server.Serve()
log.Error().Err(err).Msg("server closed")
},
}
func init() {
serveCmd.Flags().Bool("init", false, "Initializes default files at specified with the '--root' flag")
serveCmd.Flags().StringVar(&host, "host", "localhost:5050", "Set the configurator server host (can be set with CONFIGURATOR_HOST)")
serveCmd.Flags().StringVar(&rootPath, "root", "./", "Set the root path to serve files (can be set with CONFIGURATOR_ROOT)")
serveCmd.Flags().IntVarP(&timeout, "timeout", "t", 60, "Set the timeout in seconds for requests.")
rootCmd.AddCommand(serveCmd)
}