film/base/httputil/httpget.go

50 lines
998 B
Go
Raw Normal View History

2023-04-07 23:51:09 +08:00
package httputil
import (
"crypto/tls"
"fmt"
2023-04-08 20:33:48 +08:00
"github.com/spf13/cast"
2023-04-07 23:51:09 +08:00
"io"
"net/http"
"net/url"
"time"
)
// Get 请求 link请求url
2023-04-08 20:33:48 +08:00
func HttpGet(link string, params map[string]interface{}, header map[string]interface{}) ([]byte, error) {
2023-04-07 23:51:09 +08:00
client := &http.Client{Timeout: 20 * time.Second}
//忽略https的证书
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
p := url.Values{}
u, _ := url.Parse(link)
if params != nil {
for k, v := range params {
2023-04-08 20:33:48 +08:00
p.Set(k, cast.ToString(v))
2023-04-07 23:51:09 +08:00
}
}
u.RawQuery = p.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
if header != nil {
for k, v := range header {
2023-04-08 20:33:48 +08:00
req.Header.Add(k, cast.ToString(v))
2023-04-07 23:51:09 +08:00
}
}
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)
}