rest.go 903 B

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