-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
199 lines (165 loc) · 4.56 KB
/
Copy pathmain.go
File metadata and controls
199 lines (165 loc) · 4.56 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
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
package main
import (
"bufio"
"context"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type Feedback struct {
Name string `json:"name"`
Message string `json:"message"`
Rating int `json:"rating"`
Timestamp time.Time `json:"timestamp"`
}
var PORT string = ":8080"
var FILE string = "feedback.ndjson"
const QueueSize = 1000
func main() {
feedbackChan := make(chan Feedback, QueueSize)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// goroutine
go fileWriterLoop(ctx, FILE, feedbackChan)
mux := http.NewServeMux()
fs := http.FileServer(http.Dir("public"))
mux.Handle("/public/", http.StripPrefix("/public/", fs))
mux.HandleFunc("GET /add", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "public/add.html")
})
mux.HandleFunc("GET /list", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "public/list.html")
})
mux.HandleFunc("GET /feedback", func(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(FILE)
if err != nil {
if os.IsNotExist(err) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode([]Feedback{})
return
}
http.Error(w, "file open failed: "+err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
var items []Feedback
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
var fb Feedback
if err := json.Unmarshal(line, &fb); err != nil {
// continue
http.Error(w, "invalid ndjson line: "+err.Error(), http.StatusInternalServerError)
return
}
items = append(items, fb)
}
if err := scanner.Err(); err != nil {
http.Error(w, "scanner error: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(items)
})
// POST
mux.HandleFunc("POST /feedback", func(w http.ResponseWriter, r *http.Request) {
var fb Feedback
if err := json.NewDecoder(r.Body).Decode(&fb); err != nil {
http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest)
return
}
fb.Name = strings.TrimSpace(fb.Name)
fb.Message = strings.TrimSpace(fb.Message)
if fb.Name == "" || fb.Message == "" {
http.Error(w, "name and message is required", http.StatusBadRequest)
return
}
if fb.Rating < 1 || fb.Rating > 5 {
http.Error(w, "rating should be between 1-5", http.StatusBadRequest)
return
}
if fb.Timestamp.IsZero() {
fb.Timestamp = time.Now().UTC()
}
// Add to queue
select {
case feedbackChan <- fb:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]string{"status": "queued"})
return
default:
http.Error(w, "queue full, try again", http.StatusServiceUnavailable)
return
}
})
server := &http.Server{
Addr: PORT,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
log.Printf("server listening on http://localhost%s", PORT)
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
<-ch
log.Println("shutdown requested")
cancel()
ctxTimeout, cancelTimeout := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelTimeout()
_ = server.Shutdown(ctxTimeout)
}()
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("server failed: %v", err)
}
}
func fileWriterLoop(ctx context.Context, path string, in <-chan Feedback) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("writer: openfile failed: %v", err)
}
defer f.Close()
writer := bufio.NewWriterSize(f, 64*1024)
enc := json.NewEncoder(writer)
flushTicker := time.NewTicker(500 * time.Millisecond)
defer flushTicker.Stop()
for {
select {
case <-ctx.Done():
drainAndFlush(enc, writer, in)
return
case fb := <-in:
if err := enc.Encode(fb); err != nil {
log.Printf("writer: encode failed: %v", err)
}
case <-flushTicker.C:
if err := writer.Flush(); err != nil {
log.Printf("writer: flush failed: %v", err)
}
}
}
}
func drainAndFlush(enc *json.Encoder, w *bufio.Writer, in <-chan Feedback) {
for {
select {
case fb := <-in:
if err := enc.Encode(fb); err != nil {
log.Printf("writer: encode failed during drain: %v", err)
}
default:
if err := w.Flush(); err != nil {
log.Printf("writer: flush failed during draing: %v", err)
}
return
}
}
}