clash/component/resource/vehicle.go

83 lines
1.5 KiB
Go
Raw Normal View History

package resource
2019-12-08 04:17:24 +00:00
import (
"context"
2023-07-16 03:10:07 +00:00
"errors"
2021-10-09 12:35:06 +00:00
"io"
2019-12-08 04:17:24 +00:00
"net/http"
2021-10-09 12:35:06 +00:00
"os"
2019-12-08 04:17:24 +00:00
"time"
2023-07-16 03:10:07 +00:00
2023-11-03 13:01:45 +00:00
mihomoHttp "github.com/metacubex/mihomo/component/http"
types "github.com/metacubex/mihomo/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 (f *FileVehicle) Proxy() string {
return ""
}
2019-12-08 04:17:24 +00:00
func NewFileVehicle(path string) *FileVehicle {
return &FileVehicle{path: path}
}
type HTTPVehicle struct {
url string
path string
proxy string
header http.Header
2019-12-08 04:17:24 +00:00
}
2022-11-04 18:24:08 +00:00
func (h *HTTPVehicle) Url() string {
return h.url
}
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) Proxy() string {
return h.proxy
}
2019-12-08 04:17:24 +00:00
func (h *HTTPVehicle) Read() ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
resp, err := mihomoHttp.HttpRequestWithProxy(ctx, h.url, http.MethodGet, h.header, nil, h.proxy)
if err != nil {
return nil, err
}
defer resp.Body.Close()
2023-07-16 03:43:18 +00:00
if resp.StatusCode < 200 || resp.StatusCode > 299 {
2023-07-16 03:10:07 +00:00
return nil, errors.New(resp.Status)
}
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, proxy string, header http.Header) *HTTPVehicle {
return &HTTPVehicle{url, path, proxy, header}
2019-12-08 04:17:24 +00:00
}