@@ -15,6 +15,7 @@ import (
1515 "slices"
1616 "sort"
1717 "strings"
18+ "time"
1819
1920 "github.com/Masterminds/semver"
2021 "github.com/c4milo/unpackit"
@@ -412,6 +413,10 @@ func (gb *GoBrew) getGobrewVersion() string {
412413}
413414
414415func (gb * GoBrew ) getGolangVersions () (result []string ) {
416+ if result = gb .getVersionsFromCache (); len (result ) > 0 {
417+ return result
418+ }
419+
415420 data := doRequest (gb .GobrewTags )
416421 if len (data ) == 0 {
417422 return
@@ -430,7 +435,9 @@ func (gb *GoBrew) getGolangVersions() (result []string) {
430435 }
431436 }
432437
433- return
438+ gb .saveVersionsToCache (result )
439+
440+ return result
434441}
435442
436443func doRequest (url string ) (data []byte ) {
@@ -514,3 +521,52 @@ func askForConfirmation(s string) bool {
514521 }
515522 }
516523}
524+
525+ type Cache struct {
526+ Timestamp string `json:"timestamp"`
527+ Versions []string `json:"versions"`
528+ }
529+
530+ func (gb * GoBrew ) getVersionsFromCache () []string {
531+ cacheFile := filepath .Join (gb .installDir , "cache.json" )
532+ if _ , err := os .Stat (cacheFile ); err == nil {
533+ data , e := os .ReadFile (cacheFile )
534+ if e != nil {
535+ return []string {}
536+ }
537+
538+ var cache Cache
539+ if e = json .Unmarshal (data , & cache ); e != nil {
540+ return []string {}
541+ }
542+
543+ timestamp , e := time .Parse (time .RFC3339 , cache .Timestamp )
544+ if e != nil {
545+ return []string {}
546+ }
547+
548+ // cache for 20 minutes
549+ if time .Now ().UTC ().After (timestamp .Add (20 * time .Minute )) {
550+ return []string {}
551+ }
552+
553+ return cache .Versions
554+ }
555+
556+ return []string {}
557+ }
558+
559+ func (gb * GoBrew ) saveVersionsToCache (versions []string ) {
560+ cacheFile := filepath .Join (gb .installDir , "cache.json" )
561+ var cache = Cache {
562+ Timestamp : time .Now ().UTC ().Format (time .RFC3339 ),
563+ Versions : versions ,
564+ }
565+ data , err := json .Marshal (& cache )
566+ if err != nil {
567+ return
568+ }
569+
570+ // #nosec G306
571+ _ = os .WriteFile (cacheFile , data , 0600 )
572+ }
0 commit comments