loading.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. "net/http"
  19. "strings"
  20. )
  21. // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in
  22. func LoadFromFileOrHTTP(path string) ([]byte, error) {
  23. return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes)(path)
  24. }
  25. // LoadStrategy returns a loader function for a given path or uri
  26. func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
  27. if strings.HasPrefix(path, "http") {
  28. return remote
  29. }
  30. return local
  31. }
  32. func loadHTTPBytes(path string) ([]byte, error) {
  33. resp, err := http.Get(path)
  34. if err != nil {
  35. return nil, err
  36. }
  37. defer resp.Body.Close()
  38. if resp.StatusCode != http.StatusOK {
  39. return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
  40. }
  41. return ioutil.ReadAll(resp.Body)
  42. }