makeshift/cmd/serve.go

89 lines
2.4 KiB
Go

package cmd
import (
"net/url"
"time"
"git.towk2.me/towk/makeshift/pkg/service"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var serveCmd = &cobra.Command{
Use: "serve",
Example: `
# start the service in current directory
makeshift serve
# start the service with root path and initialize
makeshift serve --root ./test --init -l debug
`,
Args: cobra.NoArgs,
PreRun: func(cmd *cobra.Command, args []string) {
setenv(cmd, "host", "MAKESHIFT_HOST")
setenv(cmd, "root", "MAKESHIFT_ROOT")
setenv(cmd, "timeout", "MAKESHIFT_TIMEOUT")
},
Run: func(cmd *cobra.Command, args []string) {
var (
host, _ = cmd.Flags().GetString("host")
rootPath, _ = cmd.Flags().GetString("root")
timeout, _ = cmd.Flags().GetInt("timeout")
parsed *url.URL
server *service.Service
err error
)
// parse the host to remove scheme if needed
parsed, err = url.Parse(host)
if err != nil {
log.Warn().Err(err).
Str("host", host).
Msg("could not parse host")
}
// set the server values
server = service.New()
server.Addr = parsed.Host
server.RootPath = rootPath
server.Timeout = time.Duration(timeout) * time.Second
// show some debugging information
log.Debug().
Str("host", parsed.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") {
err = server.Init()
if err != nil {
log.Error().Err(err).
Str("host", parsed.Host).
Str("root", rootPath).
Msg("failed to initialize server root")
return
}
}
// 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().String("host", "localhost:5050", "Set the configurator server host (can be set with MAKESHIFT_HOST)")
serveCmd.Flags().String("root", "./", "Set the root path to serve files (can be set with MAKESHIFT_ROOT)")
serveCmd.Flags().IntP("timeout", "t", 60, "Set the timeout in seconds for requests (can be set with MAKESHIFT_TIMEOUT)")
rootCmd.AddCommand(serveCmd)
}