From 23411fc23dcf82e0ed35a780bfdda2341bedf819 Mon Sep 17 00:00:00 2001 From: Jeff Halter <868228+jhalter@users.noreply.github.com> Date: Wed, 8 Jun 2022 20:54:07 -0700 Subject: Add flag to enable optional stats HTTP endpoint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit re: #29 TODO: add more stat counters Usage: ``` ./mobius-hotline-server -stats-port 5503 ``` ``` ❯ curl -s localhost:5503 | jq . { "LoginCount": 0, "StartTime": "2022-06-08T20:49:10.183921-07:00", "DownloadCounter": 0, "UploadCounter": 0 } ``` --- cmd/mobius-hotline-server/main.go | 31 ++++++++++++++++++++++++ cmd/mobius-hotline-server/mobius-hotline-server | Bin 0 -> 9616722 bytes 2 files changed, 31 insertions(+) create mode 100755 cmd/mobius-hotline-server/mobius-hotline-server (limited to 'cmd/mobius-hotline-server') diff --git a/cmd/mobius-hotline-server/main.go b/cmd/mobius-hotline-server/main.go index 60327a8..8a3135e 100644 --- a/cmd/mobius-hotline-server/main.go +++ b/cmd/mobius-hotline-server/main.go @@ -2,12 +2,16 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "github.com/jhalter/mobius/hotline" "go.uber.org/zap" "go.uber.org/zap/zapcore" + "io" + "log" "math/rand" + "net/http" "os" "runtime" "time" @@ -23,6 +27,7 @@ func main() { ctx, cancelRoot := context.WithCancel(context.Background()) basePort := flag.Int("bind", defaultPort, "Bind address and port") + statsPort := flag.String("stats-port", "", "Enable stats HTTP endpoint on address and port") configDir := flag.String("config", defaultConfigPath(), "Path to config root") version := flag.Bool("version", false, "print version and exit") logLevel := flag.String("log-level", "info", "Log level") @@ -53,10 +58,36 @@ func main() { logger.Fatal(err) } + sh := statHandler{hlServer: srv} + if *statsPort != "" { + http.HandleFunc("/", sh.RenderStats) + + go func(srv *hotline.Server) { + // Use the default DefaultServeMux. + err = http.ListenAndServe(":"+*statsPort, nil) + if err != nil { + log.Fatal(err) + } + }(srv) + } + // Serve Hotline requests until program exit logger.Fatal(srv.ListenAndServe(ctx, cancelRoot)) } +type statHandler struct { + hlServer *hotline.Server +} + +func (sh *statHandler) RenderStats(w http.ResponseWriter, _ *http.Request) { + u, err := json.Marshal(sh.hlServer.Stats) + if err != nil { + panic(err) + } + + _, _ = io.WriteString(w, string(u)) +} + func newStdoutCore(level zapcore.Level) zapcore.Core { encoderCfg := zap.NewProductionEncoderConfig() encoderCfg.TimeKey = "timestamp" diff --git a/cmd/mobius-hotline-server/mobius-hotline-server b/cmd/mobius-hotline-server/mobius-hotline-server new file mode 100755 index 0000000..6d785f9 Binary files /dev/null and b/cmd/mobius-hotline-server/mobius-hotline-server differ -- cgit