/
server.go
59 lines (50 loc) · 1.29 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
package pkg
import (
"encoding/json"
"fmt"
"net/http"
)
type HTTPServer struct {
settings *Settings
dataStore *DataStore
}
func (hs *HTTPServer) Start() error {
mux := http.NewServeMux()
mux.HandleFunc("/", hs.citiesHandlerFunc())
httpServer := http.Server{
Addr: fmt.Sprintf(":%d", hs.settings.Port),
Handler: mux,
}
return (&httpServer).ListenAndServe()
}
func (hs *HTTPServer) citiesHandlerFunc() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, fmt.Sprintf("doesn't support method %s", r.Method), http.StatusMethodNotAllowed)
return
}
cities, err := hs.dataStore.GetCities()
if err != nil {
http.Error(w, "can't produce json payload", http.StatusInternalServerError)
return
}
payload, err := json.Marshal(cities)
if err != nil {
http.Error(w, "can't produce json payload", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(payload)
if err != nil {
http.Error(w, "can't produce json payload", http.StatusInternalServerError)
return
}
}
}
func NewHTTPServer(settings *Settings, datastore *DataStore) *HTTPServer {
return &HTTPServer{
settings: settings,
dataStore: datastore,
}
}