Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
106 lines (90 loc) · 2.23 KB
/
Copy pathmain.go
File metadata and controls
106 lines (90 loc) · 2.23 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"log/slog"
"os"
"runtime"
"github.com/spf13/cobra"
alog "common.queueb.org/alog"
"queueb.org/http-echo/cmd/app"
"queueb.org/http-echo/cmd/common"
"queueb.org/http-echo/pkg"
)
const (
appName = "http-echo"
//: env variables
//: exit codes
exitOk = 0
exitCommandError = 2
)
var (
appVersion = pkg.Version()
logger *alog.Logger
// Exit function
Exit = func(code int) {
os.Exit(code)
}
rootCmd = &cobra.Command{
Use: appName,
Short: "a simple web application",
Example: "httpecho server",
}
versionCmd = &cobra.Command{
Use: "version",
Aliases: []string{"ver", "V"},
Example: "version",
Run: func(cmd *cobra.Command, args []string) {
version := fmt.Sprintf(
"%[1]s version: %[2]s, %[3]s/%[4]s %[5]s",
appName, appVersion, runtime.GOOS, runtime.GOARCH, runtime.Version())
fmt.Println(version)
},
}
)
func exit(err error) {
if err == nil {
Exit(exitOk)
// this return makes sense only for testing, due to
// there's no real system exit from this function, thus far
// running in tests it will continue to follow the code sequence.
return
}
Exit(exitCommandError)
}
func init() {
//: processing flags
rootCmd.PersistentFlags().AddFlagSet(common.GlobalFlags)
//: registering local commands
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(app.NewCommands()...)
}
func appInfo(logLevel slog.Level) []any {
return []any{
slog.Group("http-echo",
slog.String("version", appVersion),
slog.String("log-level", alog.LogLevelString(logLevel)),
),
slog.Group("golang",
slog.String("version", runtime.Version()),
slog.String("arch", runtime.GOARCH),
),
}
}
func main() {
alog.SetEnv(common.AppEnv)
logLevel := alog.ParseVerbosity()
logger = alog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: false, // if true it works, but in the scope of main only.
Level: logLevel,
ReplaceAttr: alog.DefaultReplaceAttr,
}))
alog.ReplaceDefault(logger)
alog.Default().Trace("started", appInfo(logLevel)...)
//: registering local commands
rootCmd.AddGroup(
&cobra.Group{ID: common.CobraGroupMain, Title: "Main:"},
&cobra.Group{ID: common.CobraGroupAux, Title: "Aux:"},
)
err := rootCmd.Execute()
exit(err)
}