diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 0000000..4654cd0 --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,32 @@ +package cache + +import ( + "fmt" + "time" + + "github.com/patrickmn/go-cache" +) + +var Cache = cache.New(5*time.Minute, 5*time.Minute) + +const ( + GithubMessageCacheKey = "github_message" +) + +func SetCache(key string, data interface{}) bool { + fmt.Println("SET CACHE! KEY: ", key, " DATA: ", data) + Cache.Set(key, data, 1*time.Minute) + return true +} +func GetCache(key string) (string, bool) { + var ( + data string + found bool + ) + result, found := Cache.Get(key) + if found { + data = result.(string) + fmt.Println("CACHE FOUND! KEY", key, " DATA: ", data) + } + return data, found +} diff --git a/main.go b/main.go index 328ebfe..dc99989 100644 --- a/main.go +++ b/main.go @@ -2,26 +2,37 @@ package main import ( "encoding/json" + "fmt" "io/ioutil" "log" "net/http" + + "github.com/cache-in-go/cache" ) func github(w http.ResponseWriter, r *http.Request) { + // get cache + cacheData, found := cache.GetCache(cache.GithubMessageCacheKey) + if found && cacheData != "" { + json.NewEncoder(w).Encode(cacheData) + return + } + fmt.Println("GET GITHUB STATUS") resp, err := http.Get("https://api.github.com/status") if err != nil { json.NewEncoder(w).Encode(err) } data, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() + fmt.Println("DATA: ", string(data)) + // set mapcache + cache.SetCache(cache.GithubMessageCacheKey, string(data)) json.NewEncoder(w).Encode(string(data)) } - func handleRequests() { http.HandleFunc("/github", github) log.Fatal(http.ListenAndServe(":10000", nil)) } - func main() { handleRequests() }