2019-12-08 12:17:24 +08:00
|
|
|
package provider
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2020-04-20 21:22:23 +08:00
|
|
|
"net/url"
|
2019-12-08 12:17:24 +08:00
|
|
|
"time"
|
2020-02-09 17:02:48 +08:00
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/component/dialer"
|
2021-07-04 20:32:59 +08:00
|
|
|
types "github.com/Dreamacro/clash/constant/provider"
|
2019-12-08 12:17:24 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type FileVehicle struct {
|
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
2021-07-04 20:32:59 +08:00
|
|
|
func (f *FileVehicle) Type() types.VehicleType {
|
|
|
|
return types.File
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (f *FileVehicle) Path() string {
|
|
|
|
return f.path
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *FileVehicle) Read() ([]byte, error) {
|
|
|
|
return ioutil.ReadFile(f.path)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewFileVehicle(path string) *FileVehicle {
|
|
|
|
return &FileVehicle{path: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
type HTTPVehicle struct {
|
|
|
|
url string
|
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
2021-07-04 20:32:59 +08:00
|
|
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
|
|
|
return types.HTTP
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HTTPVehicle) Path() string {
|
|
|
|
return h.path
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-04-20 21:22:23 +08:00
|
|
|
uri, err := url.Parse(h.url)
|
2019-12-08 12:17:24 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-04-20 21:22:23 +08:00
|
|
|
|
|
|
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if user := uri.User; user != nil {
|
|
|
|
password, _ := user.Password()
|
|
|
|
req.SetBasicAuth(user.Username(), password)
|
|
|
|
}
|
|
|
|
|
2019-12-08 12:17:24 +08:00
|
|
|
req = req.WithContext(ctx)
|
|
|
|
|
|
|
|
transport := &http.Transport{
|
|
|
|
// from http.DefaultTransport
|
|
|
|
MaxIdleConns: 100,
|
|
|
|
IdleConnTimeout: 90 * time.Second,
|
|
|
|
TLSHandshakeTimeout: 10 * time.Second,
|
|
|
|
ExpectContinueTimeout: 1 * time.Second,
|
2020-02-09 17:02:48 +08:00
|
|
|
DialContext: dialer.DialContext,
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
client := http.Client{Transport: transport}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-12-29 11:28:22 +08:00
|
|
|
defer resp.Body.Close()
|
2019-12-30 23:01:24 +08:00
|
|
|
|
2019-12-08 12:17:24 +08:00
|
|
|
buf, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
|
|
|
return &HTTPVehicle{url, path}
|
|
|
|
}
|