http_json.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 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. package utils
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. )
  22. // GetJSON makes an HTTP call to the specified URL and parses the returned JSON into `out`.
  23. func GetJSON(url string, out interface{}) error {
  24. resp, err := http.Get(url)
  25. if err != nil {
  26. return err
  27. }
  28. return ReadJSON(resp, out)
  29. }
  30. // ReadJSON reads JSON from http.Response and parses it into `out`
  31. func ReadJSON(resp *http.Response, out interface{}) error {
  32. defer resp.Body.Close()
  33. if resp.StatusCode >= 400 {
  34. body, err := ioutil.ReadAll(resp.Body)
  35. if err != nil {
  36. return err
  37. }
  38. return fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
  39. }
  40. if out == nil {
  41. io.Copy(ioutil.Discard, resp.Body)
  42. return nil
  43. }
  44. decoder := json.NewDecoder(resp.Body)
  45. return decoder.Decode(out)
  46. }