go-emlid/reach/client/protocol/v2/http/json.go

42 lines
704 B
Go

package http
import (
"encoding/json"
"io"
"net/http"
"github.com/pkg/errors"
)
func GetJSON(url string, dst any) error {
var res *http.Response
res, err := http.Get(url)
if err != nil {
return errors.WithStack(err)
}
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
return errors.Errorf("unexpected http status code %d (%s)", res.StatusCode, res.Status)
}
defer func() {
if err := res.Body.Close(); err != nil {
errors.WithStack(err)
}
}()
var body []byte
body, err = io.ReadAll(res.Body)
if err != nil {
return errors.WithStack(err)
}
if err = json.Unmarshal(body, dst); err != nil {
return errors.WithStack(err)
}
return nil
}