enterprise/base/util/http.go

80 lines
1.6 KiB
Go
Raw Normal View History

2023-08-04 18:27:37 +08:00
package util
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net/http"
"os"
"time"
)
// Get 请求 link请求url
func HttpGet(link string, header map[string]string) ([]byte, error) {
client := &http.Client{Timeout: 20 * time.Second}
req, err := http.NewRequest("GET", link, nil)
if err != nil {
return nil, err
}
if header != nil {
for k, v := range header {
req.Header.Add(k, v)
}
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%d:%s", resp.StatusCode, resp.Status)
}
return io.ReadAll(resp.Body)
}
func Donwload(link string, localFile string) error {
res, err := http.Get(link)
if err != nil {
return err
}
f, err := os.Create(localFile)
if err != nil {
return err
}
io.Copy(f, res.Body)
return nil
}
// PostJson 请求
func HttpPostJson(link string, header map[string]string, json []byte) ([]byte, error) {
client := &http.Client{Timeout: 20 * time.Second}
//忽略https的证书
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
req, err := http.NewRequest("POST", link, bytes.NewBuffer(json))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
if header != nil {
for k, v := range header {
req.Header.Set(k, v)
}
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%d:%s", resp.StatusCode, resp.Status)
}
return io.ReadAll(resp.Body)
}