glider/proxy/dialer.go

68 lines
1.5 KiB
Go
Raw Normal View History

package proxy
import (
"errors"
"net"
"net/url"
"strings"
"github.com/nadoo/glider/common/log"
)
// Dialer is used to create connection.
type Dialer interface {
2020-04-13 12:26:21 +08:00
TCPDialer
UDPDialer
}
2020-04-14 00:17:46 +08:00
// TCPDialer is used to create tcp connection.
2020-04-13 12:26:21 +08:00
type TCPDialer interface {
// Addr is the dialer's addr
Addr() string
// Dial connects to the given address
Dial(network, addr string) (c net.Conn, err error)
2020-04-13 12:26:21 +08:00
}
2020-04-14 00:17:46 +08:00
// UDPDialer is used to create udp PacketConn.
2020-04-13 12:26:21 +08:00
type UDPDialer interface {
// Addr is the dialer's addr
Addr() string
// DialUDP connects to the given address
2018-01-17 00:26:38 +08:00
DialUDP(network, addr string) (pc net.PacketConn, writeTo net.Addr, err error)
}
2018-06-26 17:00:13 +08:00
// DialerCreator is a function to create dialers.
type DialerCreator func(s string, dialer Dialer) (Dialer, error)
var (
dialerCreators = make(map[string]DialerCreator)
)
// RegisterDialer is used to register a dialer.
func RegisterDialer(name string, c DialerCreator) {
dialerCreators[name] = c
}
2018-06-26 17:00:13 +08:00
// DialerFromURL calls the registered creator to create dialers.
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function.
2018-03-24 19:57:46 +08:00
func DialerFromURL(s string, dialer Dialer) (Dialer, error) {
if dialer == nil {
return nil, errors.New("DialerFromURL: dialer cannot be nil")
}
u, err := url.Parse(s)
if err != nil {
log.F("parse err: %s", err)
return nil, err
}
c, ok := dialerCreators[strings.ToLower(u.Scheme)]
if ok {
return c(s, dialer)
}
2018-06-03 13:54:16 +08:00
return nil, errors.New("unknown scheme '" + u.Scheme + "'")
}