-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
61 lines (51 loc) · 1.22 KB
/
handler.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
package metrica
import (
"encoding/json"
"net/http"
"sync"
"time"
"log/slog"
)
type countResponse struct {
Count int64
}
// Handler returns a http.Handler for new endpoints.
func Handler(fs *FileStorage) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/countfs", func(w http.ResponseWriter, r *http.Request) {
counterFs(w, r, fs)
})
return mux
}
func counterFs(w http.ResponseWriter, _ *http.Request, fs *FileStorage) {
var wg sync.WaitGroup
var counter int64
c := Counter(time.Now())
for i := 0; i < 1; i++ {
wg.Add(1)
go func() {
defer wg.Done()
err := fs.Write(c)
if err != nil {
send(w, http.StatusInternalServerError, err)
return
}
counters, err := fs.Read()
if err != nil {
send(w, http.StatusInternalServerError, err)
return
}
counter = counters.Count60sec()
}()
}
wg.Wait()
send(w, http.StatusOK, countResponse{Count: counter})
}
func send(w http.ResponseWriter, statusCode int, body interface{}) {
const jsonContentType = "application/json; charset=utf-8"
w.Header().Set("Content-Type", jsonContentType)
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(body); err != nil {
slog.Error("Unable to encode body as JSON", "error", err)
}
}