vehicle.go 1.5 KB

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