Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,40 @@ package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"

"github.com/patrickmn/go-cache"
)

var (
cacheSystem *cache.Cache
)

const (
CacheKeyGithubResponse = "github_response"

CacheTTLGithubResponse = time.Minute * 3
)

func github(w http.ResponseWriter, r *http.Request) {
cacheData, isFound := getCache(CacheKeyGithubResponse)
if isFound {
json.NewEncoder(w).Encode(cacheData)
return
}

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()

setCache(CacheKeyGithubResponse, string(data))
json.NewEncoder(w).Encode(string(data))
}

Expand All @@ -23,5 +45,24 @@ func handleRequests() {
}

func main() {
initCache()
handleRequests()
}

func initCache() {
cacheSystem = cache.New(5*time.Minute, 10*time.Minute)
if cacheSystem == nil {
log.Fatal("Failed to init cache")
}
}

func setCache(cacheKey string, data string) {
cacheSystem.Set(cacheKey, data, CacheTTLGithubResponse)
log.Println(fmt.Sprintf("Set cache success for key %s", cacheKey)) // log if needed
}

func getCache(cacheKey string) (data interface{}, isFound bool) {
data, isFound = cacheSystem.Get(cacheKey)

return data, isFound
}