Skip to content

Commit

Permalink
cache results for 1 hour
Browse files Browse the repository at this point in the history
  • Loading branch information
jpillora committed Feb 25, 2017
1 parent 21ebbdb commit 3055df9
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import (
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"text/template"
"time"

"github.com/jpillora/opts"
)
Expand All @@ -34,6 +37,10 @@ func main() {
}
}

const (
cacheTTL = time.Hour
)

var (
userRe = `(\/([\w\-]+))?`
repoRe = `([\w\-\_]+)`
Expand All @@ -45,8 +52,16 @@ var (
isHomebrewRe = regexp.MustCompile(`(?i)^homebrew`)
posixOSRe = regexp.MustCompile(`(darwin|linux|(net|free|open)bsd)`)
archRe = regexp.MustCompile(`(arm|386|amd64)`)
cache = map[string]cacheItem{}
cacheMut = sync.Mutex{}
)

type cacheItem struct {
added time.Time
assets []asset
release string
}

func install(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "https://github.com/jpillora/installer", http.StatusMovedPermanently)
Expand Down Expand Up @@ -162,6 +177,16 @@ type asset struct {
}

func getAssets(user, repo, release string) ([]asset, string, error) {
//cached?
key := strings.Join([]string{user, repo, release}, "|")
cacheMut.Lock()
ci, ok := cache[key]
cacheMut.Unlock()
if ok && time.Now().Sub(ci.added) < cacheTTL {
return ci.assets, ci.release, nil
}
//not cached - ask github
log.Printf("fetching asset info for %s/%s@%s", user, repo, release)
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases", user, repo)
ghas := []ghAsset{}
if release == "" {
Expand Down Expand Up @@ -216,6 +241,10 @@ func getAssets(user, repo, release string) ([]asset, string, error) {
if len(assets) == 0 {
return nil, "", errors.New("No downloads found for this release")
}
//success store results
cacheMut.Lock()
cache[key] = cacheItem{time.Now(), assets, release}
cacheMut.Unlock()
return assets, release, nil
}

Expand Down

0 comments on commit 3055df9

Please sign in to comment.