-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
225 lines (183 loc) · 5.59 KB
/
service.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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
// curl -X POST -H "Content-Type: application/json" -d '{"key": "key1", "value": "value1"}' http://localhost:8080/set
// curl -X POST -H "Content-Type: application/json" -d '{"key": "key1"}' http://localhost:8080/get
type Key string
type Value string
type SetRequest struct {
ReqestID string `json:"string"`
Key Key `json:"key"`
Value Value `json:"value"`
}
type GetRequest struct {
ReqestID string `json:"string"`
Key Key `json:"key"`
}
type GetResponse struct {
Value Value `json:"value"`
}
type ServerConfig struct {
ServiceName string
ServerAddress string
ShutdownTimeout time.Duration
EnableLoggingMiddleware bool
ServiceVersion string
}
type KeyValueStore struct {
sync.Mutex
kvMap map[Key]Value
}
// go build -ldflags "-X main.version=1.5.0" -o main service.go
var version string //TODO: Consinder to not use global variable
func main() {
// there is a hierarchy: provided flags, then environment variables, then default values
var (
serverPort = flag.String("address", useEnvOrDefaultIfNotSet(os.Getenv("SERVER_ADDRESS"), "localhost:8080").(string), "server address")
shutdownTimeout = flag.Duration("shutdown-timeout", useEnvOrDefaultIfNotSet(os.Getenv("SHUTDOWN_TIMEOUT"),
time.Second*10).(time.Duration), "shutdown timeout e.g. 10s")
enableLoggingMiddleware = flag.Bool("enable-logging-middleware",
useEnvOrDefaultIfNotSet(os.Getenv("ENABLE_LOGGING_MIDDLEWARE"), true).(bool), "enable logging middleware")
)
flag.Parse()
env := ServerConfig{
ServiceName: "key-value-service-v1",
ServerAddress: *serverPort,
ShutdownTimeout: *shutdownTimeout,
EnableLoggingMiddleware: *enableLoggingMiddleware,
ServiceVersion: version,
}
log.Println(env)
env.server()
}
// useEnvOrDefaultIfNotSet returns the value of the environment variable if it is set, otherwise it returns the default value
// this is useful for setting default values for flags but also allowing them to be overridden by environment variables
func useEnvOrDefaultIfNotSet(envValue interface{}, defaultValue interface{}) interface{} {
if envValue == nil {
return defaultValue
}
switch v := envValue.(type) {
case string:
if len(v) == 0 {
return defaultValue
}
case time.Duration:
if v == 0 {
return defaultValue.(time.Duration)
}
default:
panic(fmt.Sprintf("unexpected type %T", v))
}
return envValue
}
func (env *ServerConfig) server() {
kvStore := KeyValueStore{
kvMap: make(map[Key]Value),
}
endpoints := map[string]http.HandlerFunc{
"/healthz": LivenessProbeHandler,
"/readyz": ReadynisssProbeHandler,
"/get": kvStore.GetHandler,
"/set": kvStore.SetHandler,
}
handler := func(h http.HandlerFunc) http.HandlerFunc {
if env.EnableLoggingMiddleware {
return MiddlewareLogRequest(h)
}
return h
}
mux := http.NewServeMux()
for path, ep := range endpoints {
mux.HandleFunc(path, handler(ep))
}
// Create the server
server := http.Server{
Addr: env.ServerAddress,
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
// Start the server
go func() {
log.Println("starting server")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Failed to start server: %v", err)
}
}()
// Set up graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, os.Interrupt)
<-stop
log.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), env.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Failed to shutdown server: %v", err)
}
log.Println("Server shut down successfully")
}
func LivenessProbeHandler(w http.ResponseWriter, r *http.Request) {
// TDOO: Add more checks here, perhaps introduce global state to check if the server is still alive
w.WriteHeader(http.StatusAccepted)
}
func ReadynisssProbeHandler(w http.ResponseWriter, r *http.Request) {
// TDOO: Add more checks here, perhaps introduce global state to check if the server ready to serve requests
w.WriteHeader(http.StatusAccepted)
}
func (kv *KeyValueStore) SetHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
var payload SetRequest
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
kv.Lock()
defer kv.Unlock()
kv.kvMap[payload.Key] = payload.Value
fmt.Fprintln(w, http.StatusAccepted)
}
func (kv *KeyValueStore) GetHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var payload GetRequest
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
kv.Lock()
defer kv.Unlock()
value, ok := kv.kvMap[payload.Key]
if !ok {
http.Error(w, "Key not found", http.StatusNotFound)
return
}
response := GetResponse{Value: value}
json.NewEncoder(w).Encode(response)
}
func MiddlewareLogRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Log the request method and URL path
log.Printf("Request: %s %s %s", r.Method, r.URL.Path, r.RemoteAddr)
// Log the request headers.
for name, values := range r.Header {
for _, value := range values {
log.Printf("Header: %s=%s", name, value)
}
}
// Call the next handler in the chain
next(w, r)
}
}