8 "github.com/jhalter/mobius/hotline"
10 "go.uber.org/zap/zapcore"
25 rand.Seed(time.Now().UnixNano())
27 ctx, cancelRoot := context.WithCancel(context.Background())
29 basePort := flag.Int("bind", defaultPort, "Bind address and port")
30 statsPort := flag.String("stats-port", "", "Enable stats HTTP endpoint on address and port")
31 configDir := flag.String("config", defaultConfigPath(), "Path to config root")
32 version := flag.Bool("version", false, "print version and exit")
33 logLevel := flag.String("log-level", "info", "Log level")
37 fmt.Printf("v%s\n", hotline.VERSION)
41 zapLvl, ok := zapLogLevel[*logLevel]
43 fmt.Printf("Invalid log level %s. Must be debug, info, warn, or error.\n", *logLevel)
47 cores := []zapcore.Core{newStdoutCore(zapLvl)}
48 l := zap.New(zapcore.NewTee(cores...))
49 defer func() { _ = l.Sync() }()
52 if _, err := os.Stat(*configDir); os.IsNotExist(err) {
53 logger.Fatalw("Configuration directory not found", "path", configDir)
56 srv, err := hotline.NewServer(*configDir, "", *basePort, logger, &hotline.OSFileStore{})
61 sh := statHandler{hlServer: srv}
63 http.HandleFunc("/", sh.RenderStats)
65 go func(srv *hotline.Server) {
66 // Use the default DefaultServeMux.
67 err = http.ListenAndServe(":"+*statsPort, nil)
74 // Serve Hotline requests until program exit
75 logger.Fatal(srv.ListenAndServe(ctx, cancelRoot))
78 type statHandler struct {
79 hlServer *hotline.Server
82 func (sh *statHandler) RenderStats(w http.ResponseWriter, _ *http.Request) {
83 u, err := json.Marshal(sh.hlServer.Stats)
88 _, _ = io.WriteString(w, string(u))
91 func newStdoutCore(level zapcore.Level) zapcore.Core {
92 encoderCfg := zap.NewProductionEncoderConfig()
93 encoderCfg.TimeKey = "timestamp"
94 encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
96 return zapcore.NewCore(
97 zapcore.NewConsoleEncoder(encoderCfg),
98 zapcore.Lock(os.Stdout),
103 var zapLogLevel = map[string]zapcore.Level{
104 "debug": zap.DebugLevel,
105 "info": zap.InfoLevel,
106 "warn": zap.WarnLevel,
107 "error": zap.ErrorLevel,
110 func defaultConfigPath() (cfgPath string) {
111 switch runtime.GOOS {
115 if _, err := os.Stat("/usr/local/var/mobius/config/"); err == nil {
116 cfgPath = "/usr/local/var/mobius/config/"
117 } else if _, err := os.Stat("/opt/homebrew/var/mobius/config"); err == nil {
118 cfgPath = "/opt/homebrew/var/mobius/config/"
121 cfgPath = "/usr/local/var/mobius/config/"
123 fmt.Printf("unsupported OS")