前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言封装Http协议GET和POST请求

Go语言封装Http协议GET和POST请求

作者头像
雪飞鸿
发布2018-09-05 10:49:31
2.6K0
发布2018-09-05 10:49:31
举报
文章被收录于专栏:me的随笔me的随笔

本文几乎没有文字叙述:

代码语言:javascript
复制
/*
有关Http协议GET和POST请求的封装
*/
package net

import (
    "net/http"
    "io"
    "bytes"
    "encoding/json"
    "io/ioutil"
    "time"
)

//发送GET请求
//url:请求地址
//response:请求返回的内容
func Get(url string) (response string) {
    client := http.Client{Timeout: 5 * time.Second}
    resp, error := client.Get(url)
    defer resp.Body.Close()
    if error != nil {
        panic(error)
    }

    var buffer [512]byte
    result := bytes.NewBuffer(nil)
    for {
        n, err := resp.Body.Read(buffer[0:])
        result.Write(buffer[0:n])
        if err != nil && err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
    }

    response = result.String()
    return
}

//发送POST请求
//url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json
//content:请求放回的内容
func Post(url string, data interface{}, contentType string) (content string) {
    jsonStr, _ := json.Marshal(data)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Add("content-type", contentType)
    if err != nil {
        panic(err)
    }
    defer req.Body.Close()

    client := &http.Client{Timeout: 5 * time.Second}
    resp, error := client.Do(req)
    if error != nil {
        panic(error)
    }
    defer resp.Body.Close()

    result, _ := ioutil.ReadAll(resp.Body)
    content = string(result)
    return
}

版权声明

本文为作者原创,版权归作者雪飞鸿所有。 转载必须保留文章的完整性,且在页面明显位置处标明原文链接

如有问题, 请发送邮件和作者联系。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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