Response
The Response type represents an HTTP response.
Type Definition
type Response struct {
Status int
Headers http.Header
Body []byte
Request *Config
Stream io.ReadCloser
}Fields
Status: HTTP status codeHeaders: HTTP response headersBody: Response body bytesRequest: Original request configurationStream: Response stream (when IsStream is true)
Methods
String
Returns the response body as a string.
func (r *Response) String() stringValue
Returns the response body as a gjson.Result for JSON parsing.
func (r *Response) Value() gjson.ResultGet
Gets a JSON value by key path.
func (r *Response) Get(key string) gjson.ResultExample:
value := response.Get("user.name")
array := response.Get("items.#")JSON
Returns the response body as formatted JSON string.
func (r *Response) JSON() (string, error)UnmarshalJSON
Unmarshals the response body into a JSON struct.
func (r *Response) UnmarshalJSON(v interface{}) errorExample:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
var user User
err := response.UnmarshalJSON(&user)UnmarshalYAML
Unmarshals the response body into a YAML struct.
func (r *Response) UnmarshalYAML(v interface{}) errorOk
Returns true if status code is 2xx.
func (r *Response) Ok() boolError
Returns an error with status code and response body.
func (r *Response) Error() errorStatusCode
Returns the HTTP status code.
func (r *Response) StatusCode() intStatusText
Returns the HTTP status text.
func (r *Response) StatusText() stringContentType
Returns the Content-Type header.
func (r *Response) ContentType() stringLocation
Returns the Location header.
func (r *Response) Location() stringContentLength
Returns the Content-Length header value.
func (r *Response) ContentLength() intContentEncoding
Returns the Content-Encoding header.
func (r *Response) ContentEncoding() stringTransferEncoding
Returns the Transfer-Encoding header.
func (r *Response) TransferEncoding() stringContentLanguage
Returns the Content-Language header.
func (r *Response) ContentLanguage() stringXPoweredBy
Returns the X-Powered-By header.
func (r *Response) XPoweredBy() stringXRequestID
Returns the X-Request-ID header.
func (r *Response) XRequestID() stringAcceptRanges
Returns the Accept-Ranges header.
func (r *Response) AcceptRanges() stringSetCookie
Returns the Set-Cookie header.
func (r *Response) SetCookie() stringExample
response, err := fetch.Get("https://api.example.com/users/1")
if err != nil {
panic(err)
}
if response.Ok() {
// Parse JSON
user := response.Get("user")
fmt.Println(user.Get("name"))
// Or unmarshal to struct
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
var userObj User
err := response.UnmarshalJSON(&userObj)
fmt.Println(userObj.Name)
} else {
fmt.Printf("Error: %v\n", response.Error())
}