loading.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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/ioutil"
  18. "log"
  19. "net/http"
  20. "net/url"
  21. "path/filepath"
  22. "runtime"
  23. "strings"
  24. "time"
  25. )
  26. // LoadHTTPTimeout the default timeout for load requests
  27. var LoadHTTPTimeout = 30 * time.Second
  28. // LoadHTTPBasicAuthUsername the username to use when load requests require basic auth
  29. var LoadHTTPBasicAuthUsername = ""
  30. // LoadHTTPBasicAuthPassword the password to use when load requests require basic auth
  31. var LoadHTTPBasicAuthPassword = ""
  32. // LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests
  33. var LoadHTTPCustomHeaders = map[string]string{}
  34. // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in
  35. func LoadFromFileOrHTTP(path string) ([]byte, error) {
  36. return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path)
  37. }
  38. // LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in
  39. // timeout arg allows for per request overriding of the request timeout
  40. func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) {
  41. return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path)
  42. }
  43. // LoadStrategy returns a loader function for a given path or uri
  44. func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
  45. if strings.HasPrefix(path, "http") {
  46. return remote
  47. }
  48. return func(pth string) ([]byte, error) {
  49. upth, err := pathUnescape(pth)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if strings.HasPrefix(pth, `file://`) {
  54. if runtime.GOOS == "windows" {
  55. // support for canonical file URIs on windows.
  56. // Zero tolerance here for dodgy URIs.
  57. u, _ := url.Parse(upth)
  58. if u.Host != "" {
  59. // assume UNC name (volume share)
  60. // file://host/share/folder\... ==> \\host\share\path\folder
  61. // NOTE: UNC port not yet supported
  62. upth = strings.Join([]string{`\`, u.Host, u.Path}, `\`)
  63. } else {
  64. // file:///c:/folder/... ==> just remove the leading slash
  65. upth = strings.TrimPrefix(upth, `file:///`)
  66. }
  67. } else {
  68. upth = strings.TrimPrefix(upth, `file://`)
  69. }
  70. }
  71. return local(filepath.FromSlash(upth))
  72. }
  73. }
  74. func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) {
  75. return func(path string) ([]byte, error) {
  76. client := &http.Client{Timeout: timeout}
  77. req, err := http.NewRequest("GET", path, nil) // nolint: noctx
  78. if err != nil {
  79. return nil, err
  80. }
  81. if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" {
  82. req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword)
  83. }
  84. for key, val := range LoadHTTPCustomHeaders {
  85. req.Header.Set(key, val)
  86. }
  87. resp, err := client.Do(req)
  88. defer func() {
  89. if resp != nil {
  90. if e := resp.Body.Close(); e != nil {
  91. log.Println(e)
  92. }
  93. }
  94. }()
  95. if err != nil {
  96. return nil, err
  97. }
  98. if resp.StatusCode != http.StatusOK {
  99. return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
  100. }
  101. return ioutil.ReadAll(resp.Body)
  102. }
  103. }