github.com/gogf/gf@v1.16.9/net/ghttp/internal/client/client_response.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package client
     8  
     9  import (
    10  	"io/ioutil"
    11  	"net/http"
    12  )
    13  
    14  // Response is the struct for client request response.
    15  type Response struct {
    16  	*http.Response
    17  	request     *http.Request
    18  	requestBody []byte
    19  	cookies     map[string]string
    20  }
    21  
    22  // initCookie initializes the cookie map attribute of Response.
    23  func (r *Response) initCookie() {
    24  	if r.cookies == nil {
    25  		r.cookies = make(map[string]string)
    26  		// Response might be nil.
    27  		if r != nil && r.Response != nil {
    28  			for _, v := range r.Cookies() {
    29  				r.cookies[v.Name] = v.Value
    30  			}
    31  		}
    32  	}
    33  }
    34  
    35  // GetCookie retrieves and returns the cookie value of specified <key>.
    36  func (r *Response) GetCookie(key string) string {
    37  	r.initCookie()
    38  	return r.cookies[key]
    39  }
    40  
    41  // GetCookieMap retrieves and returns a copy of current cookie values map.
    42  func (r *Response) GetCookieMap() map[string]string {
    43  	r.initCookie()
    44  	m := make(map[string]string, len(r.cookies))
    45  	for k, v := range r.cookies {
    46  		m[k] = v
    47  	}
    48  	return m
    49  }
    50  
    51  // ReadAll retrieves and returns the response content as []byte.
    52  func (r *Response) ReadAll() []byte {
    53  	// Response might be nil.
    54  	if r == nil || r.Response == nil {
    55  		return []byte{}
    56  	}
    57  	body, err := ioutil.ReadAll(r.Response.Body)
    58  	if err != nil {
    59  		return nil
    60  	}
    61  	return body
    62  }
    63  
    64  // ReadAllString retrieves and returns the response content as string.
    65  func (r *Response) ReadAllString() string {
    66  	return string(r.ReadAll())
    67  }
    68  
    69  // Close closes the response when it will never be used.
    70  func (r *Response) Close() error {
    71  	if r == nil || r.Response == nil {
    72  		return nil
    73  	}
    74  	return r.Response.Body.Close()
    75  }