blob: 237211f8224b2da0720944f7b4afa9f6bb56bec8 [file] [log] [blame]
Girish Gowdra631ef3d2020-06-15 10:45:52 -07001// Copyright (c) 2017 Uber Technologies, Inc.
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 utils
16
17import (
18 "encoding/json"
19 "fmt"
20 "io"
21 "io/ioutil"
22 "net/http"
23)
24
25// GetJSON makes an HTTP call to the specified URL and parses the returned JSON into `out`.
26func GetJSON(url string, out interface{}) error {
27 resp, err := http.Get(url)
28 if err != nil {
29 return err
30 }
31 return ReadJSON(resp, out)
32}
33
34// ReadJSON reads JSON from http.Response and parses it into `out`
35func ReadJSON(resp *http.Response, out interface{}) error {
36 defer resp.Body.Close()
37
38 if resp.StatusCode >= 400 {
39 body, err := ioutil.ReadAll(resp.Body)
40 if err != nil {
41 return err
42 }
43
44 return fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
45 }
46
47 if out == nil {
48 io.Copy(ioutil.Discard, resp.Body)
49 return nil
50 }
51
52 decoder := json.NewDecoder(resp.Body)
53 return decoder.Decode(out)
54}