Clash.Meta/listener/inbound/base.go

80 lines
1.6 KiB
Go
Raw Normal View History

2022-12-04 13:37:14 +08:00
package inbound
import (
"encoding/json"
2022-12-04 13:37:14 +08:00
"net"
"net/netip"
"strconv"
C "github.com/Dreamacro/clash/constant"
)
type Base struct {
config *BaseOption
2022-12-04 13:37:14 +08:00
name string
preferRulesName string
listenAddr netip.Addr
port int
}
func NewBase(options *BaseOption) (*Base, error) {
if options.Listen == "" {
options.Listen = "0.0.0.0"
}
addr, err := netip.ParseAddr(options.Listen)
if err != nil {
return nil, err
}
return &Base{
name: options.Name,
listenAddr: addr,
preferRulesName: options.PreferRulesName,
port: options.Port,
config: options,
2022-12-04 13:37:14 +08:00
}, nil
}
// Config implements constant.NewListener
func (b *Base) Config() string {
return optionToString(b.config)
}
2022-12-04 13:37:14 +08:00
// Address implements constant.NewListener
func (b *Base) Address() string {
return b.RawAddress()
}
// Close implements constant.NewListener
func (*Base) Close() error {
return nil
}
// Name implements constant.NewListener
func (b *Base) Name() string {
return b.name
}
// RawAddress implements constant.NewListener
func (b *Base) RawAddress() string {
return net.JoinHostPort(b.listenAddr.String(), strconv.Itoa(int(b.port)))
}
// Listen implements constant.NewListener
2022-12-04 15:15:23 +08:00
func (*Base) Listen(tcpIn chan<- C.ConnContext, udpIn chan<- C.PacketAdapter) error {
2022-12-04 13:37:14 +08:00
return nil
}
type BaseOption struct {
Name string `inbound:"name"`
Listen string `inbound:"listen,omitempty"`
Port int `inbound:"port"`
PreferRulesName string `inbound:"rule,omitempty"`
}
var _ C.NewListener = (*Base)(nil)
func optionToString(option any) string {
str, _ := json.Marshal(option)
return string(str)
}