From 9ea44af20ee99495eb14dba10968d3fc60d210a6 Mon Sep 17 00:00:00 2001 From: natasharamdani Date: Fri, 9 Oct 2020 16:40:57 +0700 Subject: [PATCH] nanda --- main.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/main.go b/main.go index 328ebfe..f5633f6 100644 --- a/main.go +++ b/main.go @@ -2,12 +2,28 @@ package main import ( "encoding/json" + "fmt" "io/ioutil" "log" "net/http" + "time" + + "github.com/patrickmn/go-cache" ) +const cacheKey = "github" + +var c *cache.Cache + func github(w http.ResponseWriter, r *http.Request) { + dataItf := getCache() + if dataItf != nil { + dataStr := fmt.Sprintf("%v", dataItf) + json.NewEncoder(w).Encode(dataStr) + fmt.Println("get cache") + return + } + resp, err := http.Get("https://api.github.com/status") if err != nil { json.NewEncoder(w).Encode(err) @@ -15,6 +31,8 @@ func github(w http.ResponseWriter, r *http.Request) { data, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() json.NewEncoder(w).Encode(string(data)) + setCache(string(data)) + fmt.Println("get api") } func handleRequests() { @@ -23,5 +41,31 @@ func handleRequests() { } func main() { + initCache() handleRequests() + flushCache() +} + +func initCache() { + // defaultExpiration is 5 minutes + // cleanupInterval is 10 minutes, expired items will be deleted every 10 minutes + c = cache.New(5*time.Minute, 10*time.Minute) +} + +func setCache(value interface{}) { + // duration is 0, defaultExpiration will be used + c.Set(cacheKey, value, 0) +} + +func getCache() interface{} { + value, ok := c.Get(cacheKey) + if ok { + return value + } + + return nil +} + +func flushCache() { + c.Flush() }