Add GetReasonFromBody() that extracts reason from JSON
This commit is contained in:
@@ -17,8 +17,13 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/BBVA/kapow/internal/server/srverrors"
|
||||
)
|
||||
|
||||
// GetReason returns the reason phrase part of an HTTP response
|
||||
@@ -28,3 +33,22 @@ func GetReason(r *http.Response) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetReasonFromBody(r *http.Response) (string, error) {
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return "", errors.New("error reading response's body")
|
||||
}
|
||||
|
||||
reason := &srverrors.ServerErrMessage{}
|
||||
err = json.Unmarshal(body, reason)
|
||||
if err != nil {
|
||||
return "", errors.New("error unmarshaling JSON")
|
||||
}
|
||||
|
||||
if reason.Reason == "" {
|
||||
return "", errors.New("no reason")
|
||||
}
|
||||
|
||||
return reason.Reason, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user