common.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Package common contains common utilities that are shared among other packages.
  2. // See each sub-package for detail.
  3. package common
  4. import (
  5. "fmt"
  6. "go/build"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/v2fly/v2ray-core/v4/common/errors"
  15. )
  16. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  17. var (
  18. // ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route.
  19. ErrNoClue = errors.New("not enough information for making a decision")
  20. )
  21. // Must panics if err is not nil.
  22. func Must(err error) {
  23. if err != nil {
  24. panic(err)
  25. }
  26. }
  27. // Must2 panics if the second parameter is not nil, otherwise returns the first parameter.
  28. func Must2(v interface{}, err error) interface{} {
  29. Must(err)
  30. return v
  31. }
  32. // Error2 returns the err from the 2nd parameter.
  33. func Error2(v interface{}, err error) error {
  34. return err
  35. }
  36. // envFile returns the name of the Go environment configuration file.
  37. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166
  38. func envFile() (string, error) {
  39. if file := os.Getenv("GOENV"); file != "" {
  40. if file == "off" {
  41. return "", fmt.Errorf("GOENV=off")
  42. }
  43. return file, nil
  44. }
  45. dir, err := os.UserConfigDir()
  46. if err != nil {
  47. return "", err
  48. }
  49. if dir == "" {
  50. return "", fmt.Errorf("missing user-config dir")
  51. }
  52. return filepath.Join(dir, "go", "env"), nil
  53. }
  54. // GetRuntimeEnv returns the value of runtime environment variable,
  55. // that is set by running following command: `go env -w key=value`.
  56. func GetRuntimeEnv(key string) (string, error) {
  57. file, err := envFile()
  58. if err != nil {
  59. return "", err
  60. }
  61. if file == "" {
  62. return "", fmt.Errorf("missing runtime env file")
  63. }
  64. var data []byte
  65. var runtimeEnv string
  66. data, readErr := ioutil.ReadFile(file)
  67. if readErr != nil {
  68. return "", readErr
  69. }
  70. envStrings := strings.Split(string(data), "\n")
  71. for _, envItem := range envStrings {
  72. envItem = strings.TrimSuffix(envItem, "\r")
  73. envKeyValue := strings.Split(envItem, "=")
  74. if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {
  75. runtimeEnv = strings.TrimSpace(envKeyValue[1])
  76. }
  77. }
  78. return runtimeEnv, nil
  79. }
  80. // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.
  81. func GetGOBIN() string {
  82. // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command`
  83. GOBIN := os.Getenv("GOBIN")
  84. if GOBIN == "" {
  85. var err error
  86. // The one set by user by running `go env -w GOBIN=/path`
  87. GOBIN, err = GetRuntimeEnv("GOBIN")
  88. if err != nil {
  89. // The default one that Golang uses
  90. return filepath.Join(build.Default.GOPATH, "bin")
  91. }
  92. if GOBIN == "" {
  93. return filepath.Join(build.Default.GOPATH, "bin")
  94. }
  95. return GOBIN
  96. }
  97. return GOBIN
  98. }
  99. // GetGOPATH returns GOPATH environment variable as a string. It will NOT be empty.
  100. func GetGOPATH() string {
  101. // The one set by user explicitly by `export GOPATH=/path` or `env GOPATH=/path command`
  102. GOPATH := os.Getenv("GOPATH")
  103. if GOPATH == "" {
  104. var err error
  105. // The one set by user by running `go env -w GOPATH=/path`
  106. GOPATH, err = GetRuntimeEnv("GOPATH")
  107. if err != nil {
  108. // The default one that Golang uses
  109. return build.Default.GOPATH
  110. }
  111. if GOPATH == "" {
  112. return build.Default.GOPATH
  113. }
  114. return GOPATH
  115. }
  116. return GOPATH
  117. }
  118. // FetchHTTPContent dials http(s) for remote content
  119. func FetchHTTPContent(target string) ([]byte, error) {
  120. parsedTarget, err := url.Parse(target)
  121. if err != nil {
  122. return nil, newError("invalid URL: ", target).Base(err)
  123. }
  124. if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
  125. return nil, newError("invalid scheme: ", parsedTarget.Scheme)
  126. }
  127. client := &http.Client{
  128. Timeout: 30 * time.Second,
  129. }
  130. resp, err := client.Do(&http.Request{
  131. Method: "GET",
  132. URL: parsedTarget,
  133. Close: true,
  134. })
  135. if err != nil {
  136. return nil, newError("failed to dial to ", target).Base(err)
  137. }
  138. defer resp.Body.Close()
  139. if resp.StatusCode != http.StatusOK {
  140. return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
  141. }
  142. content, err := ioutil.ReadAll(resp.Body)
  143. if err != nil {
  144. return nil, newError("failed to read HTTP response").Base(err)
  145. }
  146. return content, nil
  147. }