forked from chrobson/RedisCache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
74 lines (55 loc) · 1.54 KB
/
api.go
File metadata and controls
74 lines (55 loc) · 1.54 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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type APIServer struct {
listenAddr string
database Database
}
func NewAPIServer(listenAddr string, database Database) *APIServer {
return &APIServer{
listenAddr: listenAddr,
database: database,
}
}
func (s *APIServer) Run() {
router := mux.NewRouter()
router.HandleFunc("/{id}", makeHTTPHandleFunc(s.handleGetUserById))
http.ListenAndServe(s.listenAddr, router)
}
func RenderJson(w http.ResponseWriter, val interface{}, statusCode int) error {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(statusCode)
return json.NewEncoder(w).Encode(val)
}
func (s *APIServer) handleGetUserById(w http.ResponseWriter, r *http.Request) error {
id := mux.Vars(r)["id"]
redis, err := NewRedis()
if err != nil {
log.Fatalf("Could not initialize Redis client %s", err)
}
val, err := redis.GetName(r.Context(), id)
if err == nil {
return RenderJson(w, &val, http.StatusOK)
}
person, err := s.database.GetUserById(id)
if err != nil {
return RenderJson(w, &ApiError{Error: err.Error()}, http.StatusInternalServerError)
}
_ = redis.SetName(r.Context(), *person)
return RenderJson(w, &person, http.StatusOK)
}
type apiFunc func(http.ResponseWriter, *http.Request) error
type ApiError struct {
Error string `json:"error"`
}
func makeHTTPHandleFunc(f apiFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
RenderJson(w, ApiError{Error: err.Error()}, http.StatusBadRequest)
}
}
}