bbgo_origin/pkg/util/http_response.go

59 lines
1.2 KiB
Go
Raw Normal View History

2021-02-05 14:30:47 +00:00
package util
import (
"encoding/json"
"io"
2021-02-05 14:30:47 +00:00
"net/http"
)
// Response is wrapper for standard http.Response and provides
// more methods.
type Response struct {
*http.Response
// Body overrides the composited Body field.
Body []byte
}
2021-05-23 04:11:27 +00:00
// NewResponse is a wrapper of the http.Response instance, it reads the response body and close the file.
2021-02-05 14:30:47 +00:00
func NewResponse(r *http.Response) (response *Response, err error) {
body, err := io.ReadAll(r.Body)
2021-02-05 14:30:47 +00:00
if err != nil {
return nil, err
}
err = r.Body.Close()
response = &Response{Response: r, Body: body}
return response, err
}
// String converts response body to string.
// An empty string will be returned if error.
func (r *Response) String() string {
return string(r.Body)
}
func (r *Response) DecodeJSON(o interface{}) error {
return json.Unmarshal(r.Body, o)
}
2021-02-06 01:16:43 +00:00
func (r *Response) IsError() bool {
return r.StatusCode >= 400
}
2021-02-06 02:43:25 +00:00
func (r *Response) IsJSON() bool {
switch r.Header.Get("content-type") {
case "text/json", "application/json", "application/json; charset=utf-8":
return true
}
return false
}
func (r *Response) IsHTML() bool {
switch r.Header.Get("content-type") {
case "text/html":
return true
}
return false
}