@@ -15,6 +15,7 @@ import (
15
15
"slices"
16
16
"sort"
17
17
"strings"
18
+ "time"
18
19
19
20
"github.com/Masterminds/semver"
20
21
"github.com/c4milo/unpackit"
@@ -412,6 +413,10 @@ func (gb *GoBrew) getGobrewVersion() string {
412
413
}
413
414
414
415
func (gb * GoBrew ) getGolangVersions () (result []string ) {
416
+ if result = gb .getVersionsFromCache (); len (result ) > 0 {
417
+ return result
418
+ }
419
+
415
420
data := doRequest (gb .GobrewTags )
416
421
if len (data ) == 0 {
417
422
return
@@ -430,7 +435,9 @@ func (gb *GoBrew) getGolangVersions() (result []string) {
430
435
}
431
436
}
432
437
433
- return
438
+ gb .saveVersionsToCache (result )
439
+
440
+ return result
434
441
}
435
442
436
443
func doRequest (url string ) (data []byte ) {
@@ -514,3 +521,52 @@ func askForConfirmation(s string) bool {
514
521
}
515
522
}
516
523
}
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