1 Star 0 Fork 0

linuxr/gutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
json_client.go 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
linuxr 提交于 2022-08-30 01:50 +08:00 . 重构 http client 和 errors
package http
import (
"fmt"
"net/http"
jsoniter "github.com/json-iterator/go"
)
func GetJson(url string, jsonReq interface{}) ([]byte, error) {
return GetJsonWithHeaders(url, nil, jsonReq)
}
func PostJson(url string, jsonReq interface{}) ([]byte, error) {
return PostJsonWithHeaders(url, nil, jsonReq)
}
func GetJsonWithHeaders(url string, headers map[string]string, jsonReq interface{}) ([]byte, error) {
var err error
var reqBody []byte
c := NewClient(url)
if reqBody, err = jsoniter.Marshal(jsonReq); err != nil {
return nil, err
}
if headers != nil {
c.Headers = headers
}
c.Headers["Content-Type"] = "application/json"
c.RequestData = reqBody
if err = c.Get(); err != nil {
return nil, err
}
if c.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http status code: %d", c.StatusCode)
}
return c.ResponseData, err
}
func PostJsonWithHeaders(url string, headers map[string]string, jsonReq interface{}) ([]byte, error) {
var err error
var reqBody []byte
c := NewClient(url)
if reqBody, err = jsoniter.Marshal(jsonReq); err != nil {
return nil, err
}
if headers != nil {
c.Headers = headers
}
c.Headers["Content-Type"] = "application/json"
c.RequestData = reqBody
if err = c.Post(); err != nil {
return nil, err
}
if c.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http status code: %d", c.StatusCode)
}
return c.ResponseData, err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/wangyubin/gutils.git
git@gitee.com:wangyubin/gutils.git
wangyubin
gutils
gutils
v0.4.1

搜索帮助