-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
99 lines (85 loc) · 1.95 KB
/
main.go
File metadata and controls
99 lines (85 loc) · 1.95 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
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"
"github.com/abennett/ttt/pkg/server"
)
var (
serverFS = flag.NewFlagSet("ttt", flag.ExitOnError)
port = serverFS.Int("port", 8080, "port number of server")
clientFS = flag.NewFlagSet("ttt roll", flag.ExitOnError)
)
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 := server.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)
}
}