2024-04-23 02:47:53 -04:00
|
|
|
package common
|
2023-09-12 06:40:24 -04:00
|
|
|
|
|
|
|
import (
|
2023-09-12 12:46:17 -04:00
|
|
|
"errors"
|
2023-09-12 06:40:24 -04:00
|
|
|
"net/http"
|
|
|
|
"time"
|
2024-09-17 01:10:13 -04:00
|
|
|
|
|
|
|
"github.com/nitezs/sub2clash/config"
|
2023-09-12 06:40:24 -04:00
|
|
|
)
|
|
|
|
|
2024-07-15 09:01:22 -04:00
|
|
|
type GetConfig struct {
|
|
|
|
userAgent string
|
|
|
|
}
|
|
|
|
|
|
|
|
type GetOption func(*GetConfig)
|
|
|
|
|
|
|
|
func WithUserAgent(userAgent string) GetOption {
|
|
|
|
return func(config *GetConfig) {
|
|
|
|
config.userAgent = userAgent
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Get(url string, options ...GetOption) (resp *http.Response, err error) {
|
2023-09-12 12:46:17 -04:00
|
|
|
retryTimes := config.Default.RequestRetryTimes
|
2023-09-12 06:40:24 -04:00
|
|
|
haveTried := 0
|
2024-08-11 11:55:47 -04:00
|
|
|
retryDelay := time.Second
|
2024-07-15 09:01:22 -04:00
|
|
|
getConfig := GetConfig{}
|
|
|
|
for _, option := range options {
|
|
|
|
option(&getConfig)
|
|
|
|
}
|
2023-09-12 06:40:24 -04:00
|
|
|
for haveTried < retryTimes {
|
2023-09-22 11:43:26 -04:00
|
|
|
client := &http.Client{}
|
2023-09-22 20:48:45 -04:00
|
|
|
//client.Timeout = time.Second * 10
|
2023-09-22 11:43:26 -04:00
|
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
|
|
if err != nil {
|
|
|
|
haveTried++
|
|
|
|
time.Sleep(retryDelay)
|
|
|
|
continue
|
|
|
|
}
|
2024-07-15 09:01:22 -04:00
|
|
|
if getConfig.userAgent != "" {
|
|
|
|
req.Header.Set("User-Agent", getConfig.userAgent)
|
|
|
|
}
|
2023-09-22 11:43:26 -04:00
|
|
|
get, err := client.Do(req)
|
2023-09-12 06:40:24 -04:00
|
|
|
if err != nil {
|
|
|
|
haveTried++
|
|
|
|
time.Sleep(retryDelay)
|
|
|
|
continue
|
|
|
|
} else {
|
2024-08-11 11:55:47 -04:00
|
|
|
|
2023-09-12 12:46:17 -04:00
|
|
|
if get != nil && get.ContentLength > config.Default.RequestMaxFileSize {
|
|
|
|
return nil, errors.New("文件过大")
|
|
|
|
}
|
2023-09-12 06:40:24 -04:00
|
|
|
return get, nil
|
|
|
|
}
|
2023-09-12 12:46:17 -04:00
|
|
|
|
2023-09-12 06:40:24 -04:00
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|