http_json.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3. // of this software and associated documentation files (the "Software"), to deal
  4. // in the Software without restriction, including without limitation the rights
  5. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6. // copies of the Software, and to permit persons to whom the Software is
  7. // furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in
  10. // all copies or substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. // THE SOFTWARE.
  19. package utils
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "net/http"
  26. )
  27. // GetJSON makes an HTTP call to the specified URL and parses the returned JSON into `out`.
  28. func GetJSON(url string, out interface{}) error {
  29. resp, err := http.Get(url)
  30. if err != nil {
  31. return err
  32. }
  33. return ReadJSON(resp, out)
  34. }
  35. // ReadJSON reads JSON from http.Response and parses it into `out`
  36. func ReadJSON(resp *http.Response, out interface{}) error {
  37. defer resp.Body.Close()
  38. if resp.StatusCode >= 400 {
  39. body, err := ioutil.ReadAll(resp.Body)
  40. if err != nil {
  41. return err
  42. }
  43. return fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
  44. }
  45. if out == nil {
  46. io.Copy(ioutil.Discard, resp.Body)
  47. return nil
  48. }
  49. decoder := json.NewDecoder(resp.Body)
  50. return decoder.Decode(out)
  51. }