Fetch the repository succeeded.
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。