github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/net/http/request.go (about)

     1  package http
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/qxnw/lib4go/encoding"
     9  )
    10  
    11  // NewRequest 创建新请求
    12  func (c *HTTPClient) NewRequest(method string, url string, args ...string) *HTTPClientRequest {
    13  	request := &HTTPClientRequest{}
    14  	request.client = c.client
    15  	request.headers = make(map[string]string)
    16  	request.method = strings.ToUpper(method)
    17  	request.params = ""
    18  	request.url = url
    19  	request.encoding = getEncoding(args...)
    20  	return request
    21  }
    22  
    23  // SetData 设置请求参数
    24  func (c *HTTPClientRequest) SetData(params string) {
    25  	c.params = params
    26  }
    27  
    28  // SetHeader 设置http header
    29  func (c *HTTPClientRequest) SetHeader(key string, value string) {
    30  	c.headers[key] = value
    31  }
    32  
    33  // Request 发送http请求, method:http请求方法包括:get,post,delete,put等 url: 请求的HTTP地址,不包括参数,params:请求参数,
    34  // header,http请求头多个用/n分隔,每个键值之前用=号连接
    35  func (c *HTTPClientRequest) Request() (content string, status int, err error) {
    36  	req, err := http.NewRequest(c.method, c.url, strings.NewReader(c.params))
    37  	if err != nil {
    38  		return
    39  	}
    40  	req.Close = true
    41  	for i, v := range c.headers {
    42  		req.Header.Set(i, v)
    43  	}
    44  	resp, err := c.client.Do(req)
    45  	if resp != nil {
    46  		defer resp.Body.Close()
    47  	}
    48  	if err != nil {
    49  		return
    50  	}
    51  	body, err := ioutil.ReadAll(resp.Body)
    52  	if err != nil {
    53  		return
    54  	}
    55  	status = resp.StatusCode
    56  	content, err = encoding.Convert(body, c.encoding)
    57  	return
    58  }