对 golang http 库进行封装,更优雅的调用网络接口
go get github.com/topology-zero/[email protected]
query := map[string]string{
"a": "1",
"b": "2",
}
request := httpclient.NewHttpRequest(httpclient.GET, "https://foo.com", httpclient.WithQuery(query))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
type reqStruct struct {
id int
name string
}
req := reqStruct{
id: 10086,
name: "中国移不动",
}
request := httpclient.NewHttpRequest(httpclient.POST, "https://foo.com", httpclient.WithJson(req))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
req := httpclient.UploadFile{
Field: "file",
FileName: "image.png",
File: bytes.NewReader([]byte{}),
}
request := httpclient.NewHttpRequest(httpclient.POST, "https://foo.com", httpclient.WithMultipartFrom(&req, nil))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
req := map[string]string{
"a": "1",
"b": "2",
}
request := httpclient.NewHttpRequest(httpclient.POST, "https://foo.com", httpclient.WithMultipartFrom(nil, req))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
file := httpclient.UploadFile{
Field: "file",
FileName: "image.png",
File: bytes.NewReader([]byte{}),
}
data := map[string]string{
"a": "1",
"b": "2",
}
request := httpclient.NewHttpRequest(httpclient.POST, "https://foo.com", httpclient.WithMultipartFrom(&file, data))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
req := map[string]any{
"a": 1,
"b": "2",
}
request := httpclient.NewHttpRequest(httpclient.POST, "https://foo.com", httpclient.WithFromData(req))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
type reqStruct struct {
name string
}
req := reqStruct{
name: "中国移不动",
}
request := httpclient.NewHttpRequest(httpclient.PUT, "https://foo.com/10086", httpclient.WithJson(req))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
request := httpclient.NewHttpRequest(httpclient.DELETE, "https://foo.com/10086")
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))
request := httpclient.NewHttpRequest(httpclient.DELETE, "https://foo.com/10086", httpclient.WithLog(logrus.StandardLogger()))
resp, err := request.DoHttpRequest()
if err != nil {
panic(err)
}
log.Println(string(resp))