Skip to content

Commit daf2e06

Browse files
committed
feat: add download flag -m "ustc".
in china google is not available, use ustc mirrors
1 parent 191c342 commit daf2e06

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

internal/version/version.go

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"compress/gzip"
1212
"crypto/sha256"
1313
"errors"
14+
"flag"
1415
"fmt"
1516
"io"
1617
"io/ioutil"
@@ -41,8 +42,12 @@ func Run(version string) {
4142
log.Fatalf("%s: %v", version, err)
4243
}
4344

44-
if len(os.Args) == 2 && os.Args[1] == "download" {
45-
if err := install(root, version); err != nil {
45+
if len(os.Args) >= 2 && os.Args[1] == "download" {
46+
flagset := flag.NewFlagSet("download", flag.ExitOnError)
47+
mirror := flagset.String("m", "google", "download mirror: ['google','ustc]")
48+
flagset.Parse(os.Args[2:])
49+
50+
if err := install(root, version, *mirror); err != nil {
4651
log.Fatalf("%s: download failed: %v", version, err)
4752
}
4853
os.Exit(0)
@@ -100,7 +105,7 @@ func fmtSize(size int64) string {
100105

101106
// install installs a version of Go to the named target directory, creating the
102107
// directory as needed.
103-
func install(targetDir, version string) error {
108+
func install(targetDir, version, mirror string) error {
104109
if _, err := os.Stat(filepath.Join(targetDir, unpackedOkay)); err == nil {
105110
log.Printf("%s: already downloaded in %v", version, targetDir)
106111
return nil
@@ -109,7 +114,8 @@ func install(targetDir, version string) error {
109114
if err := os.MkdirAll(targetDir, 0755); err != nil {
110115
return err
111116
}
112-
goURL := versionArchiveURL(version)
117+
goURL := versionArchiveURL(version, mirror)
118+
fmt.Printf("download from %s\n", goURL)
113119
res, err := http.Head(goURL)
114120
if err != nil {
115121
return err
@@ -417,8 +423,20 @@ func getOS() string {
417423
return runtime.GOOS
418424
}
419425

426+
// getMirrors return the download url by mirror
427+
func getMirrors(mirror string) string {
428+
switch mirror {
429+
case "ustc":
430+
return "https://mirrors.ustc.edu.cn/golang/"
431+
case "google":
432+
fallthrough
433+
default:
434+
return "https://dl.google.com/go/"
435+
}
436+
}
437+
420438
// versionArchiveURL returns the zip or tar.gz URL of the given Go version.
421-
func versionArchiveURL(version string) string {
439+
func versionArchiveURL(version, mirror string) string {
422440
goos := getOS()
423441

424442
ext := ".tar.gz"
@@ -429,7 +447,7 @@ func versionArchiveURL(version string) string {
429447
if goos == "linux" && runtime.GOARCH == "arm" {
430448
arch = "armv6l"
431449
}
432-
return "https://dl.google.com/go/" + version + "." + goos + "-" + arch + ext
450+
return getMirrors(mirror) + version + "." + goos + "-" + arch + ext
433451
}
434452

435453
const caseInsensitiveEnv = runtime.GOOS == "windows"

0 commit comments

Comments
 (0)