go笔记:go发起http get请求

2019-11-22 09:37:35 浏览数 (1)

直接上代码:

代码语言:javascript复制
package requests

import (
    "bytes"
    "io"
    "io/ioutil"
    "net/http"
    urltools "net/url"
    "strings"
    "time"

    "git.code.oa.com/bigdata/gobase/logging"
)

var trans *http.Transport

func init() {
    trans = &http.Transport{
        MaxIdleConns:        1000,
        MaxIdleConnsPerHost: 500,
        IdleConnTimeout:     90 * time.Second,
    }
}

// Request 发起一个请求,会将body的数据返回成string。如果错误,则返回emptyStr
// method: POST GET DELETE PUT
// body:可传空,或者你想要的,比如 `{"text":"hello"}`
// timeout:你懂的
func Request(method string, url string, body string, timeout int64) string {
    var bodyIO io.Reader
    if body != "" {
        bodyIO = strings.NewReader(body)
    } else {
        bodyIO = nil
    }

    client := http.Client{
        Transport: trans,
        Timeout:   time.Duration(timeout) * time.Second,
    }

    request, err := http.NewRequest(method, url, bodyIO)
    if err != nil {
        logging.Errorf("Request NewRequest err %v", err)
        return ""
    }

    response, err := client.Do(request)
    if response != nil {
        defer response.Body.Close()
    }
    if err != nil {
        logging.Errorf("Request %v", err)
        return ""
    }
    contents, err := ioutil.ReadAll(response.Body)
    if err != nil {
        logging.Errorf("Request readbody err %v", err)
        return ""
    }
    return string(contents)
}

type ReqBody struct {
    body []byte
}

func NewReqBody(body interface{}) *ReqBody {
    b := new(ReqBody)
    switch v := body.(type) {
    case string:
        b.body = []byte(v)
    case []byte:
        b.body = v
    default:
        panic("NewReqBody body must be []byte or string")
    }
    return b
}

type ReqHeader struct {
    header map[string]string
}

func NewReqHeader() *ReqHeader {
    header := new(ReqHeader)
    header.header = make(map[string]string)
    return header
}

func (h *ReqHeader) Add(key, val string) *ReqHeader {
    h.header[key] = val
    return h
}

type ReqParams struct {
    params map[string]string
}

func NewReqParams() *ReqParams {
    p := new(ReqParams)
    p.params = make(map[string]string)
    return p
}

func (p *ReqParams) Add(key, val string) *ReqParams {
    p.params[key] = val
    return p
}

type Resp struct {
    HttpResp   *http.Response
    Body       []byte
    StatusCode int
}

/*
RequestAdvance 是一个稍微高级的http_req,允许传入header, body, urlParams等,返回值也更丰富
method: POST GET DELETE PUT
body:可传空,或者你想要的,比如 `{"text":"hello"}`
timeout:超时,秒

usage:
    resp := requests.RequestAdvance("POST", "http://localhost:9090/Echo?sys=android", 3,
        requests.NewReqBody([]byte("hello")),
        requests.NewReqHeader().Add("Auth-Token", "hello"),
        requests.NewReqParams().Add("name", "大猪").Add("pwd", "hello"),
    )
    if resp == nil {
        fmt.Println("error")
        return
    }
    fmt.Println("StatusCode", resp.StatusCode)
    fmt.Println("Body", string(resp.Body))
    fmt.Println("ContentLength", resp.HttpResp.ContentLength)
*/
func RequestAdvance(method string, url string, timeout int64, args ...interface{}) *Resp {
    var bodyIO io.Reader
    bodyIO = nil

    var header *ReqHeader
    header = nil

    var params *ReqParams
    params = nil

    for _, item := range args {
        switch v := item.(type) {
        case *ReqBody:
            bodyIO = bytes.NewReader(v.body)
        case *ReqHeader:
            header = v
        case *ReqParams:
            params = v
        }
    }

    client := http.Client{
        Transport: trans,
        Timeout:   time.Duration(timeout) * time.Second,
    }

    // 设置url参数
    if params != nil {
        urlObj, err := urltools.Parse(url)
        if err != nil {
            logging.Errorf("Request NewRequest url parse err, url:%v,err: %v", url, err)
            return nil
        }

        query := urlObj.Query()
        for key := range params.params {
            query.Set(key, params.params[key])
        }

        urlObj.RawQuery = query.Encode()

        url = urlObj.String()
    }

    request, err := http.NewRequest(method, url, bodyIO)
    if err != nil {
        logging.Errorf("Request NewRequest err %v", err)
        return nil
    }
    // 增加header
    if header != nil {
        for key := range header.header {
            request.Header.Set(key, header.header[key])
        }
    }

    response, err := client.Do(request)
    if response != nil {
        defer response.Body.Close()
    }
    if err != nil {
        logging.Errorf("Request %v", err)
        return nil
    }
    contents, err := ioutil.ReadAll(response.Body)
    if err != nil {
        logging.Errorf("Request readbody err %v", err)
        return nil
    }

    resp := new(Resp)
    resp.StatusCode = response.StatusCode
    resp.Body = contents
    resp.HttpResp = response
    return resp
}

0 人点赞