-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
92 lines (83 loc) · 2.05 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
package main
import (
"bytes"
"context"
_ "embed"
"fmt"
"github.com/eclipse/paho.golang/paho"
"github.com/perbu/whippet/whippet"
"io"
"log/slog"
"os"
"os/signal"
"syscall"
)
//go:embed .version
var embeddedVersion string
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
err := run(ctx, os.Stderr, os.Stdout, os.Stdin, os.Args[1:], os.Environ())
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
}
func run(ctx context.Context, logoutput, output io.Writer, input io.Reader, args, env []string) error {
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
logHandle := slog.NewTextHandler(logoutput, &slog.HandlerOptions{Level: slog.LevelDebug})
logger := slog.New(logHandle)
config, showhelp, err := whippet.GetConfig(args)
if err != nil {
return fmt.Errorf("getConfig: %w", err)
}
if showhelp {
return nil
}
logger.Info("whippet starting up", "version", embeddedVersion)
client, msgChan, err := whippet.Connect(runCtx, config, logger)
if err != nil {
return fmt.Errorf("connect: %w", err)
}
go func() {
<-runCtx.Done()
logger.Info("context cancelled, disconnecting client")
if client != nil {
d := &paho.Disconnect{ReasonCode: 0}
_ = client.Disconnect(d)
}
// Just assume the rest of the application is able to shut down
}()
// read the input until OEF
payload, err := read(ctx, input)
if err != nil {
return fmt.Errorf("read: %w", err)
}
response, err := whippet.Request(runCtx, client, config, payload, msgChan, logger)
if err != nil {
return fmt.Errorf("request: %w", err)
}
_, err = output.Write(response)
if err != nil {
return fmt.Errorf("output.Write: %w", err)
}
return nil
}
func read(ctx context.Context, input io.Reader) ([]byte, error) {
var buf bytes.Buffer
done := make(chan error, 1)
go func() {
_, err := io.Copy(&buf, input)
done <- err
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case err := <-done:
if err != nil {
return nil, fmt.Errorf("io.Copy: %w", err)
}
return buf.Bytes(), nil
}
}