rest.go 656 B

12345678910111213141516171819202122232425262728293031
  1. package rest
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. )
  8. // JSONDecoder decodes json from given io.ReadCloser to target object.
  9. func JSONDecoder(data io.ReadCloser, target interface{}) error {
  10. decoder := json.NewDecoder(data)
  11. err := decoder.Decode(target)
  12. return err
  13. }
  14. // GET returns io.ReadCloser of response body. Don't forget to close it.
  15. func GET(url string) (io.ReadCloser, error) {
  16. resp, err := http.Get(url)
  17. if err != nil {
  18. return nil, fmt.Errorf("Response error: %v", err)
  19. }
  20. if resp.StatusCode != http.StatusOK {
  21. return resp.Body, fmt.Errorf("Request unsuccessful: %v - %v", resp.Status, url)
  22. }
  23. return resp.Body, nil
  24. }