github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_client_response.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"io/ioutil"
    11  	"net/http"
    12  	"time"
    13  )
    14  
    15  // 客户端请求结果对象
    16  type ClientResponse struct {
    17  	*http.Response
    18  	cookies map[string]string
    19  }
    20  
    21  // 获得返回的指定COOKIE值
    22  func (r *ClientResponse) GetCookie(key string) string {
    23  	if r.cookies == nil {
    24  		now := time.Now()
    25  		for _, v := range r.Cookies() {
    26  			if v.Expires.UnixNano() < now.UnixNano() {
    27  				continue
    28  			}
    29  			r.cookies[v.Name] = v.Value
    30  		}
    31  	}
    32  	return r.cookies[key]
    33  }
    34  
    35  // 获取返回的数据(二进制).
    36  func (r *ClientResponse) ReadAll() []byte {
    37  	body, err := ioutil.ReadAll(r.Body)
    38  	if err != nil {
    39  		return nil
    40  	}
    41  	return body
    42  }
    43  
    44  // 获取返回的数据(字符串).
    45  func (r *ClientResponse) ReadAllString() string {
    46  	return string(r.ReadAll())
    47  }
    48  
    49  // 关闭返回的HTTP链接
    50  func (r *ClientResponse) Close() error {
    51  	r.Response.Close = true
    52  	return r.Body.Close()
    53  }