glang 多种http请求

2020-08-03T16:02:50
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
func HttpGet(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        // handle error
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
        return nil, err
    }
    return body, err
}

func HttpPostForm(queryUrl string, queryData map[string]string) ([]byte, error) {
    // )
    if len(queryData) == 0 || queryUrl == "" {
        return nil, errors.New("参数错误")
    }

    url.Parse(queryUrl)
    urlValue := url.Values{}
    for k, v := range queryData {
        var valList = make([]string, 1)
        valList[0] = v
        urlValue[k] = valList
    }
    resp, err := http.PostForm(queryUrl, urlValue)
    if err != nil {
        return nil, err
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    return body, nil
}
func HttpPostJson(queryUrl string, queryData map[string]string) ([]byte, error) {
    if len(queryData) == 0 || queryUrl == "" {
        return nil, errors.New("参数错误")
    }

    jsonStr, err := json.Marshal(queryData)
    if err != nil {
        return nil, errors.New("json编码出错")
    }
    // jsonStr := []byte()
    req, err := http.NewRequest("POST", queryUrl, bytes.NewBuffer([]byte(jsonStr)))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    return body, nil
}
扫一扫关注公众号添加购物返利助手,领红包
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »
因本文不是用Markdown格式的编辑器书写的,转换的页面可能不符合MIP标准。