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