Go语言写个通用的http请求发送和接收函数
以下是一个通用的 Go 语言 HTTP 请求发送和接收函数的示例:
import (
"net/http"
"io/ioutil"
)
// 发送 HTTP 请求并返回响应内容和错误
func httpRequest(method, url string, headers map[string]string, body []byte) ([]byte, error) {
// 创建一个 http 请求
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
// 设置请求头
for k, v := range headers {
req.Header.Set(k, v)
}
// 发送请求并获取响应
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// 读取响应内容
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respBody, nil
}
使用示例:
// 发送 GET 请求
resp, err := httpRequest("GET", "http://example.com", nil, nil)
if err != nil {
// 处理错误
}
fmt.Println(string(resp))
// 发送 POST 请求
headers := map[string]string{"Content-Type": "application/json"}
body := []byte(`{"name":"John","age":30}`)
resp, err = httpRequest("POST", "http://example.com/api", headers, body)
if err != nil {
// 处理错误
}
fmt.Println(string(resp))
``
原文地址: https://www.cveoy.top/t/topic/fuAW 著作权归作者所有。请勿转载和采集!