1 // Copyright 2015 go-swagger maintainers
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
27 // LoadHTTPTimeout the default timeout for load requests
28 var LoadHTTPTimeout = 30 * time.Second
30 // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in
31 func LoadFromFileOrHTTP(path string) ([]byte, error) {
32 return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path)
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
37 func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) {
38 return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path)
41 // LoadStrategy returns a loader function for a given path or uri
42 func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) {
43 if strings.HasPrefix(path, "http") {
46 return func(pth string) ([]byte, error) {
47 upth, err := pathUnescape(pth)
51 return local(filepath.FromSlash(upth))
55 func 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)
62 resp, err := client.Do(req)
65 if e := resp.Body.Close(); e != nil {
74 if resp.StatusCode != http.StatusOK {
75 return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status)
78 return ioutil.ReadAll(resp.Body)