github.com/metacubex/mihomo@v1.18.5/component/resource/vehicle.go (about) 1 package resource 2 3 import ( 4 "context" 5 "errors" 6 "io" 7 "net/http" 8 "os" 9 "time" 10 11 mihomoHttp "github.com/metacubex/mihomo/component/http" 12 types "github.com/metacubex/mihomo/constant/provider" 13 ) 14 15 type FileVehicle struct { 16 path string 17 } 18 19 func (f *FileVehicle) Type() types.VehicleType { 20 return types.File 21 } 22 23 func (f *FileVehicle) Path() string { 24 return f.path 25 } 26 27 func (f *FileVehicle) Read() ([]byte, error) { 28 return os.ReadFile(f.path) 29 } 30 31 func (f *FileVehicle) Proxy() string { 32 return "" 33 } 34 35 func NewFileVehicle(path string) *FileVehicle { 36 return &FileVehicle{path: path} 37 } 38 39 type HTTPVehicle struct { 40 url string 41 path string 42 proxy string 43 header http.Header 44 } 45 46 func (h *HTTPVehicle) Url() string { 47 return h.url 48 } 49 50 func (h *HTTPVehicle) Type() types.VehicleType { 51 return types.HTTP 52 } 53 54 func (h *HTTPVehicle) Path() string { 55 return h.path 56 } 57 58 func (h *HTTPVehicle) Proxy() string { 59 return h.proxy 60 } 61 62 func (h *HTTPVehicle) Read() ([]byte, error) { 63 ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) 64 defer cancel() 65 resp, err := mihomoHttp.HttpRequestWithProxy(ctx, h.url, http.MethodGet, h.header, nil, h.proxy) 66 if err != nil { 67 return nil, err 68 } 69 defer resp.Body.Close() 70 if resp.StatusCode < 200 || resp.StatusCode > 299 { 71 return nil, errors.New(resp.Status) 72 } 73 buf, err := io.ReadAll(resp.Body) 74 if err != nil { 75 return nil, err 76 } 77 return buf, nil 78 } 79 80 func NewHTTPVehicle(url string, path string, proxy string, header http.Header) *HTTPVehicle { 81 return &HTTPVehicle{url, path, proxy, header} 82 }