123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package swag
- import (
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- "path/filepath"
- "strings"
- "time"
- )
- var LoadHTTPTimeout = 30 * time.Second
- func LoadFromFileOrHTTP(path string) ([]byte, error) {
- return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path)
- }
- func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) {
- return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path)
- }
- func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
- if strings.HasPrefix(path, "http") {
- return remote
- }
- return func(pth string) ([]byte, error) {
- upth, err := pathUnescape(pth)
- if err != nil {
- return nil, err
- }
- return local(filepath.FromSlash(upth))
- }
- }
- func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) {
- return func(path string) ([]byte, error) {
- client := &http.Client{Timeout: timeout}
- req, err := http.NewRequest("GET", path, nil)
- if err != nil {
- return nil, err
- }
- resp, err := client.Do(req)
- defer func() {
- if resp != nil {
- if e := resp.Body.Close(); e != nil {
- log.Println(e)
- }
- }
- }()
- if err != nil {
- return nil, err
- }
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
- }
- return ioutil.ReadAll(resp.Body)
- }
- }
|