-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
263 lines (240 loc) · 6.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"time"
"golang.org/x/sync/errgroup"
)
type requestMsg struct {
Msg string
}
type responseMsg struct {
Msg string
}
const ContentTypeNdJson = "application/x-ndjson"
func client(ctx context.Context, address string) error {
client := http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: nil,
Timeout: 0,
}
var resp *http.Response
var w *io.PipeWriter
for {
// explicitly set r to be a io.Reader, as if not, NewRequestWithContext tries to close the reader before returning as PipeReader fulfills ReadeCloser interface
var r *io.PipeReader
r, w = io.Pipe()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, address, r)
if err != nil {
return fmt.Errorf("failed to create request, error was: %w", err)
}
req.Header.Set("Accept", ContentTypeNdJson)
req.Header.Set("Content-Type", ContentTypeNdJson)
select {
case <-ctx.Done():
slog.Info("client: context was done, exiting")
return nil
default:
// fall-through
}
resp, err = client.Do(req)
if err != nil {
slog.Info("client: failed to start request against server", "error", err)
time.Sleep(1 * time.Second)
continue
}
if resp.StatusCode != http.StatusOK {
slog.Info("client: failed to start request against server", "statuscode", resp.StatusCode)
time.Sleep(1 * time.Second)
continue
}
break
}
defer resp.Body.Close()
enc := json.NewEncoder(w)
dec := json.NewDecoder(resp.Body)
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ctx.Done():
slog.Info("client: context was done, exiting")
return nil
case <-ticker.C:
err := enc.Encode(requestMsg{
Msg: "ping",
})
if err != nil {
if !errors.Is(err, io.EOF) {
return fmt.Errorf("client: failed to encode request message to server, error was: %w", err)
}
return nil
}
_, err = io.WriteString(w, "\n")
if err != nil {
if !errors.Is(err, io.EOF) {
return fmt.Errorf("client: failed to send newline to server, error was: %w", err)
}
return nil
}
slog.Debug("client: posted ping to server")
var in responseMsg
err = dec.Decode(&in)
if err != nil {
if !errors.Is(err, io.EOF) {
return fmt.Errorf("failed to decode response message from server, error was: %w", err)
}
return nil
}
slog.Debug("client: received message from server", "msg", in.Msg)
}
}
}
func server(ctx context.Context, hostPort string) error {
mux := http.NewServeMux()
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
if method := request.Method; method != http.MethodPost {
writer.Header().Set("Allow", http.MethodPost)
writer.WriteHeader(http.StatusMethodNotAllowed)
slog.Info("server: client attempted to connect with wrong method instead of POST", "wrong_method", method)
return
}
if contentType := request.Header.Get("Content-Type"); contentType != ContentTypeNdJson {
writer.WriteHeader(http.StatusUnsupportedMediaType)
slog.Info("server: client attempted to connect with wrong content-type instead of "+ContentTypeNdJson, "wrong_content_type", contentType)
return
}
if accepts := request.Header.Get("Accept"); accepts != ContentTypeNdJson {
writer.WriteHeader(http.StatusNotAcceptable)
slog.Info("server: client requested data in wrong format instead of "+ContentTypeNdJson, "wrong_accept", accepts)
return
}
respCtl := http.NewResponseController(writer)
err := respCtl.EnableFullDuplex()
if err != nil {
slog.Warn("failed to enable full duplex on http writer", "error", err)
return
}
var inMsg requestMsg
outMsg := responseMsg{Msg: "pong"}
dec := json.NewDecoder(request.Body)
enc := json.NewEncoder(writer)
// to get the communication going
writer.WriteHeader(http.StatusOK)
err = respCtl.Flush()
if err != nil {
slog.Error("server: failed to flush status header to client", "error", err)
return
}
slog.Info("server: wrote status ok to client")
for {
select {
case <-request.Context().Done():
return
case <-ctx.Done():
return
default:
err := dec.Decode(&inMsg)
if err != nil {
if !errors.Is(err, io.ErrUnexpectedEOF) {
slog.Error("server: failed to receive request message from client", "error", err)
return
}
slog.Info("server: client closed connection - finished")
return
}
slog.Debug("server: received message from client", "msg", inMsg.Msg)
err = enc.Encode(outMsg)
if err != nil {
if !errors.Is(err, io.ErrUnexpectedEOF) {
slog.Error("server: failed to send respond message to client", "error", err)
return
}
slog.Info("server: client closed connection - finished")
return
}
_, err = io.WriteString(writer, "\n")
if err != nil {
if !errors.Is(err, io.EOF) {
slog.Error("server: failed to send newline to client", "error", err)
}
slog.Info("server: client closed connection - finished")
return
}
err = respCtl.Flush()
if err != nil {
slog.Error("server: failed to flush request message to client", "error", err)
return
}
slog.Debug("server: sent pong to client")
}
}
})
server := http.Server{
Addr: hostPort,
Handler: mux,
DisableGeneralOptionsHandler: false,
TLSConfig: nil,
ReadTimeout: 0,
ReadHeaderTimeout: 0,
WriteTimeout: 0,
IdleTimeout: 0,
MaxHeaderBytes: 0,
TLSNextProto: nil,
ConnState: nil,
ErrorLog: nil,
BaseContext: nil,
ConnContext: nil,
}
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
err := server.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
})
eg.Go(func() error {
<-ctx.Done()
slog.Info("server: context was done, shutting down server")
timeoutCtx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFunc()
defer slog.Info("server: finished shutting down")
return server.Shutdown(timeoutCtx)
})
return eg.Wait()
}
func main() {
var level slog.Level = slog.LevelInfo
hostPort := "localhost:8080"
flag.TextVar(&level, "log-level", level, "set log level")
flag.StringVar(&hostPort, "hostport", hostPort, "set hostPort")
flag.Parse()
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: false,
Level: level,
ReplaceAttr: nil,
})))
ctx, cancelFunc := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancelFunc()
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error { return server(ctx, hostPort) })
eg.Go(func() error { return client(ctx, "http://"+hostPort) })
eg.Go(func() error {
<-ctx.Done()
slog.Info("signal: interrupt signal received")
return nil
})
err := eg.Wait()
if err != nil {
panic(err)
}
}