-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (85 loc) · 1.97 KB
/
main.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
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
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/abennett/ttt/pkg"
)
var (
serverFS = flag.NewFlagSet("ttt", flag.ExitOnError)
port = serverFS.Int("port", 8080, "port number of server")
clientFS = flag.NewFlagSet("ttt roll", flag.ExitOnError)
logFile = clientFS.String("logfile", "", "log to a file")
)
var (
serveCmd = &ffcli.Command{
Name: "serve",
FlagSet: serverFS,
Exec: serve,
}
rollCmd = &ffcli.Command{
Name: "roll",
FlagSet: clientFS,
ShortUsage: "roll <host_with_protocol> <room> <username>",
Exec: rollRemote,
}
)
func health(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}
func serve(ctx context.Context, args []string) error {
h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug})
slog.SetDefault(slog.New(h))
server := pkg.NewServer()
r := chi.NewRouter()
r.Use(middleware.DefaultLogger)
r.Get("/{roomName}", server.ServeHTTP)
r.Get("/health", health)
port := ":" + strconv.Itoa(*port)
slog.Info("serving", "port", port)
return http.ListenAndServe(port, r)
}
var diceRollCmd = &ffcli.Command{
Name: "roll_local",
Exec: func(ctx context.Context, args []string) error {
if len(args) == 0 {
fmt.Println("a roll argument is required")
return nil
}
dr, err := pkg.ParseDiceRoll(args[0])
if err != nil {
return err
}
fmt.Printf("%s => %d\n", args[0], dr.Roll())
return nil
},
}
func main() {
root := &ffcli.Command{
ShortUsage: "ttt <subcommand>",
Subcommands: []*ffcli.Command{
diceRollCmd,
serveCmd,
rollCmd,
},
Exec: func(context.Context, []string) error {
return flag.ErrHelp
},
}
err := root.Parse(os.Args[1:])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = root.Run(context.Background())
if err != nil && err != flag.ErrHelp {
fmt.Println(err)
}
}