Clash.Meta/adapters/outbound/selector.go

87 lines
1.6 KiB
Go
Raw Normal View History

package adapters
import (
2018-11-21 13:47:46 +08:00
"encoding/json"
"errors"
2018-12-22 23:56:42 +08:00
"net"
C "github.com/Dreamacro/clash/constant"
)
type Selector struct {
2018-12-22 23:56:42 +08:00
*Base
selected C.Proxy
proxies map[string]C.Proxy
proxyList []string
}
type SelectorOption struct {
Name string `proxy:"name"`
Proxies []string `proxy:"proxies"`
}
func (s *Selector) Dial(metadata *C.Metadata) (C.Conn, error) {
c, err := s.selected.Dial(metadata)
if err == nil {
c.AppendToChains(s)
}
return c, err
}
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
pc, addr, err := s.selected.DialUDP(metadata)
if err == nil {
pc.AppendToChains(s)
}
return pc, addr, err
2019-04-23 23:29:36 +08:00
}
func (s *Selector) SupportUDP() bool {
return s.selected.SupportUDP()
}
2018-11-21 13:47:46 +08:00
func (s *Selector) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"type": s.Type().String(),
"now": s.Now(),
"all": s.proxyList,
2018-11-21 13:47:46 +08:00
})
}
func (s *Selector) Now() string {
return s.selected.Name()
}
func (s *Selector) Set(name string) error {
2018-07-18 21:50:16 +08:00
proxy, exist := s.proxies[name]
if !exist {
return errors.New("Proxy does not exist")
}
s.selected = proxy
return nil
}
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
2018-07-18 21:50:16 +08:00
if len(proxies) == 0 {
return nil, errors.New("Provide at least one proxy")
}
mapping := make(map[string]C.Proxy)
proxyList := make([]string, len(proxies))
for idx, proxy := range proxies {
mapping[proxy.Name()] = proxy
proxyList[idx] = proxy.Name()
}
s := &Selector{
2018-12-22 23:56:42 +08:00
Base: &Base{
name: name,
tp: C.Selector,
},
proxies: mapping,
selected: proxies[0],
proxyList: proxyList,
}
return s, nil
}