Skip to content

Commit 0649b7a

Browse files
committed
go-cache implementation
revision
1 parent 8e7cfa5 commit 0649b7a

2 files changed

Lines changed: 45 additions & 2 deletions

File tree

cache/cache.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package cache
2+
3+
import (
4+
"fmt"
5+
"time"
6+
7+
"github.com/patrickmn/go-cache"
8+
)
9+
10+
var Cache = cache.New(5*time.Minute, 5*time.Minute)
11+
12+
const (
13+
GithubMessageCacheKey = "github_message"
14+
)
15+
16+
func SetCache(key string, data interface{}) bool {
17+
fmt.Println("SET CACHE! KEY: ", key, " DATA: ", data)
18+
Cache.Set(key, data, 1*time.Minute)
19+
return true
20+
}
21+
func GetCache(key string) (string, bool) {
22+
var (
23+
data string
24+
found bool
25+
)
26+
result, found := Cache.Get(key)
27+
if found {
28+
data = result.(string)
29+
fmt.Println("CACHE FOUND! KEY", key, " DATA: ", data)
30+
}
31+
return data, found
32+
}

main.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,37 @@ package main
22

33
import (
44
"encoding/json"
5+
"fmt"
56
"io/ioutil"
67
"log"
78
"net/http"
9+
10+
"github.com/cache-in-go/cache"
811
)
912

1013
func github(w http.ResponseWriter, r *http.Request) {
14+
// get cache
15+
cacheData, found := cache.GetCache(cache.GithubMessageCacheKey)
16+
if found && cacheData != "" {
17+
json.NewEncoder(w).Encode(cacheData)
18+
return
19+
}
20+
fmt.Println("GET GITHUB STATUS")
1121
resp, err := http.Get("https://api.github.com/status")
1222
if err != nil {
1323
json.NewEncoder(w).Encode(err)
1424
}
1525
data, _ := ioutil.ReadAll(resp.Body)
1626
resp.Body.Close()
27+
fmt.Println("DATA: ", string(data))
28+
// set mapcache
29+
cache.SetCache(cache.GithubMessageCacheKey, string(data))
1730
json.NewEncoder(w).Encode(string(data))
1831
}
19-
2032
func handleRequests() {
2133
http.HandleFunc("/github", github)
2234
log.Fatal(http.ListenAndServe(":10000", nil))
2335
}
24-
2536
func main() {
2637
handleRequests()
2738
}

0 commit comments

Comments
 (0)