-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
137 lines (127 loc) · 3.39 KB
/
server.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
package main
import (
"context"
"encoding/json"
"errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"io"
"log"
"log/slog"
"net/http"
"time"
)
type HTTPServer struct {
addr string
mntPoint string
store *KVStore
logger *slog.Logger
}
func NewHTTPServer(addr, mntPoint string, store *KVStore, logger *slog.Logger) *HTTPServer {
return &HTTPServer{
addr: addr,
mntPoint: mntPoint,
store: store,
logger: logger,
}
}
func (s *HTTPServer) Serve(ctx context.Context) error {
srv := &http.Server{
Addr: s.addr,
Handler: s.Routes(),
}
shutdownCh := make(chan struct{})
go func(ctx context.Context) {
<-ctx.Done()
s.logger.Info("Shutting down kvstore http server")
tCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := srv.Shutdown(tCtx); err != nil {
s.logger.Error("Error shutting down kvstore http server, force closing",
"err", err.Error())
_ = srv.Close()
}
close(shutdownCh)
}(ctx)
s.logger.Info("Starting kvstore http server")
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
<-shutdownCh
return nil
}
func (s *HTTPServer) Routes() chi.Router {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Route(s.mntPoint, func(r chi.Router) {
r.Get("/{key}", s.Get)
r.Post("/", s.Post)
r.Put("/{key}", s.Put)
})
return r
}
func (s *HTTPServer) Get(w http.ResponseWriter, r *http.Request) {
key := chi.URLParam(r, "key")
v, ok, err := s.store.Get(key)
if err != nil && errors.Is(err, ErrStoreNotReady) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
if !ok {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
_, _ = w.Write([]byte(v))
}
func (s *HTTPServer) Put(w http.ResponseWriter, r *http.Request) {
key := chi.URLParam(r, "key")
value, err := io.ReadAll(r.Body)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
_, ok, err := s.store.Get(key)
if !ok {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
err = s.store.Put(key, string(value))
if err != nil && errors.Is(err, ErrStoreNotReady) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
}
}
func (s *HTTPServer) Post(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
if err != nil {
s.logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var e map[string]string
err = json.Unmarshal(data, &e)
if err != nil {
s.logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
key, value := e["key"], e["value"]
_, ok, err := s.store.Get(key)
if ok {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
s.logger.Info("POST request", slog.String("key", key), slog.String("value", value))
err = s.store.Put(key, value)
if err != nil {
if errors.Is(err, ErrStoreNotReady) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte("OK"))
}