http urls monitor.

loading.go 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "path/filepath"
  21. "strings"
  22. "time"
  23. )
  24. // LoadHTTPTimeout the default timeout for load requests
  25. var LoadHTTPTimeout = 30 * time.Second
  26. // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in
  27. func LoadFromFileOrHTTP(path string) ([]byte, error) {
  28. return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path)
  29. }
  30. // LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in
  31. // timeout arg allows for per request overriding of the request timeout
  32. func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) {
  33. return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path)
  34. }
  35. // LoadStrategy returns a loader function for a given path or uri
  36. func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
  37. if strings.HasPrefix(path, "http") {
  38. return remote
  39. }
  40. return func(pth string) ([]byte, error) {
  41. upth, err := pathUnescape(pth)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return local(filepath.FromSlash(upth))
  46. }
  47. }
  48. func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) {
  49. return func(path string) ([]byte, error) {
  50. client := &http.Client{Timeout: timeout}
  51. req, err := http.NewRequest("GET", path, nil)
  52. if err != nil {
  53. return nil, err
  54. }
  55. resp, err := client.Do(req)
  56. defer func() {
  57. if resp != nil {
  58. if e := resp.Body.Close(); e != nil {
  59. log.Println(e)
  60. }
  61. }
  62. }()
  63. if err != nil {
  64. return nil, err
  65. }
  66. if resp.StatusCode != http.StatusOK {
  67. return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
  68. }
  69. return ioutil.ReadAll(resp.Body)
  70. }
  71. }