content.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2016 Google Inc. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to writing, software distributed
  8. // under the License is distributed on a "AS IS" BASIS, WITHOUT WARRANTIES OR
  9. // CONDITIONS OF ANY KIND, either express or implied.
  10. //
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package embedmd
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net/http"
  18. "path/filepath"
  19. "strings"
  20. )
  21. // Fetcher provides an abstraction on a file system.
  22. // The Fetch function is called anytime some content needs to be fetched.
  23. // For now this includes files and URLs.
  24. // The first parameter is the base directory that could be used to resolve
  25. // relative paths. This base directory will be ignored for absolute paths,
  26. // such as URLs.
  27. type Fetcher interface {
  28. Fetch(dir, path string) ([]byte, error)
  29. }
  30. type fetcher struct{}
  31. func (fetcher) Fetch(dir, path string) ([]byte, error) {
  32. if !strings.HasPrefix(path, "http://") && !strings.HasPrefix(path, "https://") {
  33. path = filepath.Join(dir, filepath.FromSlash(path))
  34. return ioutil.ReadFile(path)
  35. }
  36. res, err := http.Get(path)
  37. if err != nil {
  38. return nil, err
  39. }
  40. defer res.Body.Close()
  41. if res.StatusCode != http.StatusOK {
  42. return nil, fmt.Errorf("status %s", res.Status)
  43. }
  44. return ioutil.ReadAll(res.Body)
  45. }