clash/adapter/provider/vehicle.go

105 lines
1.9 KiB
Go
Raw Normal View History

2019-12-08 04:17:24 +00:00
package provider
import (
"context"
"github.com/Dreamacro/clash/listener/inner"
2021-10-09 12:35:06 +00:00
"io"
"net"
2019-12-08 04:17:24 +00:00
"net/http"
"net/url"
2021-10-09 12:35:06 +00:00
"os"
2019-12-08 04:17:24 +00:00
"time"
2020-02-09 09:02:48 +00:00
netHttp "github.com/Dreamacro/clash/common/net"
types "github.com/Dreamacro/clash/constant/provider"
2019-12-08 04:17:24 +00:00
)
type FileVehicle struct {
path string
}
func (f *FileVehicle) Type() types.VehicleType {
return types.File
2019-12-08 04:17:24 +00:00
}
func (f *FileVehicle) Path() string {
return f.path
}
func (f *FileVehicle) Read() ([]byte, error) {
2021-10-09 12:35:06 +00:00
return os.ReadFile(f.path)
2019-12-08 04:17:24 +00:00
}
func NewFileVehicle(path string) *FileVehicle {
return &FileVehicle{path: path}
}
type HTTPVehicle struct {
url string
path string
}
func (h *HTTPVehicle) Type() types.VehicleType {
return types.HTTP
2019-12-08 04:17:24 +00: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()
uri, err := url.Parse(h.url)
2019-12-08 04:17:24 +00:00
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
2022-04-03 11:15:16 +00:00
req.Header.Set("User-Agent", netHttp.UA)
if err != nil {
return nil, err
}
if user := uri.User; user != nil {
password, _ := user.Password()
req.SetBasicAuth(user.Username(), password)
}
2019-12-08 04:17:24 +00: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,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
conn := inner.HandleTcp(address, uri.Hostname())
return conn, nil
},
2019-12-08 04:17:24 +00:00
}
client := http.Client{Transport: transport}
resp, err := client.Do(req)
if err != nil {
if err != nil {
return nil, err
}
2019-12-08 04:17:24 +00:00
}
defer resp.Body.Close()
2019-12-30 15:01:24 +00:00
2021-10-09 12:35:06 +00:00
buf, err := io.ReadAll(resp.Body)
2019-12-08 04:17:24 +00:00
if err != nil {
return nil, err
}
return buf, nil
}
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
return &HTTPVehicle{url, path}
}