Ai
1 Star 0 Fork 0

smooe/tools

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
requests.go 2.61 KB
Copy Edit Raw Blame History
邵腾腾 authored 2023-07-03 17:34 +08:00 . update requests.go.
package tools
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"sync"
"time"
)
func Post(surl string, headers map[string]string, data any, timeout time.Duration) (http_code int, res []byte, err error) {
method := "POST"
http_code, body, err := Action(method, surl, headers, data,timeout)
if err != nil {
return http.StatusBadRequest, nil, err
}
return http_code, body, nil
}
func Delete(surl string, headers map[string]string, data any,timeout time.Duration) (http_code int, res []byte, err error) {
method := "DELETE"
http_code, body, err := Action(method, surl, headers, data,timeout)
if err != nil {
return http.StatusBadRequest, nil, err
}
return http_code, body, nil
}
func Put(surl string, headers map[string]string, data any,timeout time.Duration) (http_code int, res []byte, err error) {
method := "PUT"
http_code, body, err := Action(method, surl, headers, data,timeout)
if err != nil {
return http.StatusBadRequest, nil, err
}
return http_code, body, nil
}
func Get(surl string, headers map[string]string, data map[string]string, timeout time.Duration) (http_code int, res []byte, err error) {
client := &http.Client{Timeout: timeout}
req, err := http.NewRequest("GET", surl, nil)
q := req.URL.Query()
//urldata := url.Values{}
for k, v := range data {
q.Add(k, v)
}
//u, _ := url.ParseRequestURI(surl)
req.URL.RawQuery = q.Encode()
for k, v := range headers {
req.Header.Add(k, v)
}
if err != nil {
return 99, []byte{0}, err
}
//u.RawQuery = urldata.Encode()
rest, err := client.Do(req)
if err != nil {
return 99, []byte{}, err
}
defer rest.Body.Close()
body, _ := io.ReadAll(rest.Body)
return rest.StatusCode, body, nil
}
func Action(method, surl string, headers map[string]string, data any,timeout time.Duration) (http_code int, res []byte, err error) {
//fmt.Println(method, surl, headers, data)
var b []byte
if data != nil {
b, err = json.Marshal(data)
if err != nil {
return http_code, nil, err
}
}
req, err := http.NewRequest(method, surl, bytes.NewReader(b))
if err != nil {
return http.StatusBadRequest, nil, err
}
rheaders := make(http.Header)
if len(headers) != 0 {
for k, v := range headers {
rheaders.Add(k, v)
}
}
req.Header = rheaders
client := &http.Client{Timeout: timeout}
body, err := client.Do(req)
defer body.Body.Close()
if err != nil {
return http.StatusBadRequest, nil, nil
}
// var bodydata map[string]any
resbody, _ := io.ReadAll(body.Body)
// _ = json.Unmarshal(resbody, &bodydata)
return body.StatusCode, resbody, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/smooe/tools.git
git@gitee.com:smooe/tools.git
smooe
tools
tools
v0.0.4

Search