100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Go语言封装Http协议GET和POST请求

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

时间:2020-09-13 10:59:06

相关推荐

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

本文几乎没有文字叙述:

/*有关Http协议GET和POST请求的封装*/package netimport ("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]byteresult := 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}

版权声明

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。