2022-03-02 12:34:11 +08:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
2022-07-04 22:01:03 +08:00
|
|
|
"log"
|
2022-03-02 12:34:11 +08:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2022-06-17 13:19:53 +08:00
|
|
|
const UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
|
2022-03-02 12:34:11 +08:00
|
|
|
|
|
|
|
type HttpClient struct {
|
|
|
|
*http.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
var httpClient *HttpClient
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
httpClient = &HttpClient{http.DefaultClient}
|
2022-07-04 22:01:03 +08:00
|
|
|
httpClient.Timeout = time.Second * 60
|
2022-03-02 12:34:11 +08:00
|
|
|
httpClient.Transport = &http.Transport{
|
|
|
|
TLSHandshakeTimeout: time.Second * 5,
|
2022-07-04 22:01:03 +08:00
|
|
|
IdleConnTimeout: time.Second * 10,
|
|
|
|
ResponseHeaderTimeout: time.Second * 10,
|
2022-03-02 12:34:11 +08:00
|
|
|
ExpectContinueTimeout: time.Second * 20,
|
2022-07-29 05:54:00 +08:00
|
|
|
Proxy: http.ProxyFromEnvironment,
|
2022-03-02 12:34:11 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetHttpClient() *HttpClient {
|
|
|
|
c := *httpClient
|
|
|
|
return &c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *HttpClient) Get(urls ...string) (body []byte, err error) {
|
|
|
|
var req *http.Request
|
|
|
|
var resp *http.Response
|
|
|
|
|
|
|
|
for _, url := range urls {
|
|
|
|
req, err = http.NewRequest(http.MethodGet, url, nil)
|
|
|
|
if err != nil {
|
2022-07-04 22:01:03 +08:00
|
|
|
log.Println(err)
|
2022-03-02 12:34:11 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
req.Header.Set("User-Agent", UserAgent)
|
|
|
|
resp, err = c.Do(req)
|
|
|
|
|
|
|
|
if err == nil && resp != nil && resp.StatusCode == 200 {
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err = ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|