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

本文提供了一种使用Go语言实现的HTTP GET和POST请求封装方法。通过简单的函数调用即可发起网络请求并获取响应内容,支持设置超时时间及自定义请求头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文几乎没有文字叙述:

 

/*
有关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
}

 

版权声明

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值