-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (82 loc) · 2.03 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/pjcalvo/go-cache/cache"
"github.com/pjcalvo/go-cache/connection"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
const ttlCache = 15
func main() {
cache := cache.InitCache()
conn, err := connection.Init()
if err != nil {
panic(err)
}
r := mux.NewRouter()
r.HandleFunc("/new/{value}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
value := vars["value"]
id := uuid.New()
res := connection.Response{
Id: id.String(),
Value: value,
}
err := conn.Add(res)
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("something wrong happened when inserting: %v", err)))
return
}
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(res)
})
counter := 0
r.HandleFunc("/get/{id}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
value, err := cache.Get(key, func(key string) (value any, ttlSecs int, err error) {
// sleeps mimics operation slowness
time.Sleep(1 * time.Second)
fmt.Println("read from db")
res, err := conn.Get(key)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return nil, 0, fmt.Errorf("something wrong happened when searching: %v", err)
}
counter++
return fmt.Sprintf("%s%v", res.Value, counter), ttlCache, nil
})
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("something wrong happened when getting from cache: %v", err)))
return
}
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(value)
})
srv := http.Server{
Addr: "localhost:8080",
Handler: r,
}
// Set up a channel for handling Ctrl-C, etc
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
select {
case sig := <-sigchan:
fmt.Printf("Caught signal %v: terminating\n", sig)
srv.Close()
return
}
}
}()
fmt.Println(srv.ListenAndServe())
}