前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go笔记:go发起http get请求

go笔记:go发起http get请求

作者头像
超级大猪
发布2019-11-22 09:37:35
1K0
发布2019-11-22 09:37:35
举报
文章被收录于专栏:大猪的笔记大猪的笔记

直接上代码:

代码语言: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
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档