mihomo/adapters/outbound/selector.go

73 lines
1.3 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"
2018-08-07 14:45:24 +08:00
"sort"
C "github.com/Dreamacro/clash/constant"
)
type Selector struct {
2018-12-22 23:56:42 +08:00
*Base
selected C.Proxy
2018-07-18 21:50:16 +08:00
proxies map[string]C.Proxy
}
type SelectorOption struct {
Name string `proxy:"name"`
Proxies []string `proxy:"proxies"`
}
2018-12-22 23:56:42 +08:00
func (s *Selector) Generator(metadata *C.Metadata) (net.Conn, error) {
2018-09-30 12:25:52 +08:00
return s.selected.Generator(metadata)
}
2018-11-21 13:47:46 +08:00
func (s *Selector) MarshalJSON() ([]byte, error) {
var all []string
2018-07-18 21:50:16 +08:00
for k := range s.proxies {
all = append(all, k)
}
2018-08-07 14:45:24 +08:00
sort.Strings(all)
2018-11-21 13:47:46 +08:00
return json.Marshal(map[string]interface{}{
"type": s.Type().String(),
"now": s.Now(),
"all": all,
})
}
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)
for _, proxy := range proxies {
mapping[proxy.Name()] = proxy
}
s := &Selector{
2018-12-22 23:56:42 +08:00
Base: &Base{
name: name,
tp: C.Selector,
},
2018-07-18 21:50:16 +08:00
proxies: mapping,
selected: proxies[0],
}
return s, nil
}