github.com/chwjbn/xclash@v0.2.0/adapter/provider/parser.go (about)

     1  package provider
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/chwjbn/xclash/common/structure"
     9  	C "github.com/chwjbn/xclash/constant"
    10  	types "github.com/chwjbn/xclash/constant/provider"
    11  )
    12  
    13  var errVehicleType = errors.New("unsupport vehicle type")
    14  
    15  type healthCheckSchema struct {
    16  	Enable   bool   `provider:"enable"`
    17  	URL      string `provider:"url"`
    18  	Interval int    `provider:"interval"`
    19  	Lazy     bool   `provider:"lazy,omitempty"`
    20  }
    21  
    22  type proxyProviderSchema struct {
    23  	Type        string            `provider:"type"`
    24  	Path        string            `provider:"path"`
    25  	URL         string            `provider:"url,omitempty"`
    26  	Interval    int               `provider:"interval,omitempty"`
    27  	Filter      string            `provider:"filter,omitempty"`
    28  	HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
    29  }
    30  
    31  func ParseProxyProvider(name string, mapping map[string]interface{}) (types.ProxyProvider, error) {
    32  	decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
    33  
    34  	schema := &proxyProviderSchema{
    35  		HealthCheck: healthCheckSchema{
    36  			Lazy: true,
    37  		},
    38  	}
    39  	if err := decoder.Decode(mapping, schema); err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	var hcInterval uint
    44  	if schema.HealthCheck.Enable {
    45  		hcInterval = uint(schema.HealthCheck.Interval)
    46  	}
    47  	hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
    48  
    49  	path := C.Path.Resolve(schema.Path)
    50  
    51  	var vehicle types.Vehicle
    52  	switch schema.Type {
    53  	case "file":
    54  		vehicle = NewFileVehicle(path)
    55  	case "http":
    56  		vehicle = NewHTTPVehicle(schema.URL, path)
    57  	default:
    58  		return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
    59  	}
    60  
    61  	interval := time.Duration(uint(schema.Interval)) * time.Second
    62  	filter := schema.Filter
    63  	return NewProxySetProvider(name, interval, filter, vehicle, hc)
    64  }