-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_handler.go
More file actions
69 lines (56 loc) · 1.39 KB
/
api_handler.go
File metadata and controls
69 lines (56 loc) · 1.39 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
package persistantcache
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/loveleshsharma/persistent-cache/cache"
"github.com/loveleshsharma/persistent-cache/request"
"github.com/loveleshsharma/persistent-cache/response"
)
type APIHandler struct {
cache *cache.Cache
}
func NewApiHandler(cache *cache.Cache) APIHandler {
return APIHandler{
cache: cache,
}
}
func (h APIHandler) Get(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
value, err := h.cache.Get(key)
if err != nil {
w.Write([]byte("Key not found"))
return
}
getResp := response.GetResponse{
Value: value.(cache.Value).GetValue(),
}
bytes, _ := json.Marshal(getResp)
w.Write(bytes)
}
func (h APIHandler) Set(w http.ResponseWriter, r *http.Request) {
bytes, err := io.ReadAll(r.Body)
if err != nil {
log.Fatalln("error occurred while reading request: ", err)
return
}
var setRequest request.SetRequest
json.Unmarshal(bytes, &setRequest)
if setRequest.Expiry != 0 {
h.cache.SetWithExpiry(setRequest.Key, setRequest.Value, time.Duration(time.Minute*time.Duration(setRequest.Expiry)))
} else {
h.cache.Set(setRequest.Key, setRequest.Value)
}
setResponse := response.SetResponse{
Status: "Success",
}
resBytes, err := json.Marshal(setResponse)
if err != nil {
fmt.Println("error occurres while marshalling response", err)
return
}
w.Write(resBytes)
}