loading.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package swag
  15. import (
  16. "fmt"
  17. "io"
  18. "log"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strings"
  25. "time"
  26. )
  27. // LoadHTTPTimeout the default timeout for load requests
  28. var LoadHTTPTimeout = 30 * time.Second
  29. // LoadHTTPBasicAuthUsername the username to use when load requests require basic auth
  30. var LoadHTTPBasicAuthUsername = ""
  31. // LoadHTTPBasicAuthPassword the password to use when load requests require basic auth
  32. var LoadHTTPBasicAuthPassword = ""
  33. // LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests
  34. var LoadHTTPCustomHeaders = map[string]string{}
  35. // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in
  36. func LoadFromFileOrHTTP(path string) ([]byte, error) {
  37. return LoadStrategy(path, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path)
  38. }
  39. // LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in
  40. // timeout arg allows for per request overriding of the request timeout
  41. func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) {
  42. return LoadStrategy(path, os.ReadFile, loadHTTPBytes(timeout))(path)
  43. }
  44. // LoadStrategy returns a loader function for a given path or uri
  45. func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
  46. if strings.HasPrefix(path, "http") {
  47. return remote
  48. }
  49. return func(pth string) ([]byte, error) {
  50. upth, err := pathUnescape(pth)
  51. if err != nil {
  52. return nil, err
  53. }
  54. if strings.HasPrefix(pth, `file://`) {
  55. if runtime.GOOS == "windows" {
  56. // support for canonical file URIs on windows.
  57. // Zero tolerance here for dodgy URIs.
  58. u, _ := url.Parse(upth)
  59. if u.Host != "" {
  60. // assume UNC name (volume share)
  61. // file://host/share/folder\... ==> \\host\share\path\folder
  62. // NOTE: UNC port not yet supported
  63. upth = strings.Join([]string{`\`, u.Host, u.Path}, `\`)
  64. } else {
  65. // file:///c:/folder/... ==> just remove the leading slash
  66. upth = strings.TrimPrefix(upth, `file:///`)
  67. }
  68. } else {
  69. upth = strings.TrimPrefix(upth, `file://`)
  70. }
  71. }
  72. return local(filepath.FromSlash(upth))
  73. }
  74. }
  75. func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) {
  76. return func(path string) ([]byte, error) {
  77. client := &http.Client{Timeout: timeout}
  78. req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx
  79. if err != nil {
  80. return nil, err
  81. }
  82. if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" {
  83. req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword)
  84. }
  85. for key, val := range LoadHTTPCustomHeaders {
  86. req.Header.Set(key, val)
  87. }
  88. resp, err := client.Do(req)
  89. defer func() {
  90. if resp != nil {
  91. if e := resp.Body.Close(); e != nil {
  92. log.Println(e)
  93. }
  94. }
  95. }()
  96. if err != nil {
  97. return nil, err
  98. }
  99. if resp.StatusCode != http.StatusOK {
  100. return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
  101. }
  102. return io.ReadAll(resp.Body)
  103. }
  104. }