-
Notifications
You must be signed in to change notification settings - Fork 5
/
cli.go
74 lines (61 loc) · 1.69 KB
/
cli.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/go-chi/chi"
"github.com/mitchellh/mapstructure"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/saas-templates/go-svelte/api"
"github.com/saas-templates/go-svelte/pkg/httputils"
"github.com/saas-templates/go-svelte/pkg/log"
"github.com/saas-templates/go-svelte/ui"
)
func newCLI(ctx context.Context) *cobra.Command {
rootCmd := &cobra.Command{
Use: "go-svelte",
Short: "A short summary",
Version: fmt.Sprintf("%s\ncommit: %s\nbuilt on: %s\n", Version, Commit, BuiltAt),
}
rootCmd.SetContext(ctx)
rootCmd.PersistentFlags().StringP("config", "c", "", "Config file override")
rootCmd.AddCommand(
cmdServe(),
cmdConfigs(),
)
return rootCmd
}
func cmdServe() *cobra.Command {
cmd := &cobra.Command{
Use: "serve",
Short: "Start HTTP server",
Run: func(cmd *cobra.Command, args []string) {
cfg := loadConf(cmd)
router := chi.NewRouter()
router.Mount("/", ui.Handler())
router.Mount("/api", api.Router(cfg.API))
log.Infof(cmd.Context(), "listening at '%s'...", cfg.Addr)
if err := httputils.GracefulServe(cmd.Context(), 5*time.Second, cfg.Addr, router); err != nil {
log.Fatalf(cmd.Context(), "server exited: %v", err)
}
log.Infof(cmd.Context(), "server exited gracefully")
},
}
return cmd
}
func cmdConfigs() *cobra.Command {
return &cobra.Command{
Use: "configs",
Short: "Display current loaded configs",
Run: func(cmd *cobra.Command, args []string) {
cfg := loadConf(cmd)
m := map[string]any{}
if err := mapstructure.Decode(cfg, &m); err != nil {
log.Fatalf(cmd.Context(), "failed to decode")
}
_ = yaml.NewEncoder(os.Stdout).Encode(m)
},
}
}