glider/proxy/dialer.go

58 lines
1.2 KiB
Go
Raw Normal View History

package proxy
import (
"errors"
"net"
"net/url"
"strings"
"github.com/nadoo/glider/common/log"
)
2018-06-26 17:00:13 +08:00
// Dialer means to establish a connection and relay it.
type Dialer interface {
// Addr()
Addr() string
// Dial connects to the given address via the proxy.
Dial(network, addr string) (c net.Conn, err error)
2018-01-17 00:26:38 +08:00
// DialUDP connects to the given address via the proxy.
DialUDP(network, addr string) (pc net.PacketConn, writeTo net.Addr, err error)
// Get the dialer by dstAddr
NextDialer(dstAddr string) Dialer
}
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 (
dialerMap = make(map[string]DialerCreator)
)
2018-06-26 17:00:13 +08:00
// RegisterDialer is used to register a dialer
func RegisterDialer(name string, c DialerCreator) {
dialerMap[name] = c
}
2018-06-26 17:00:13 +08:00
// DialerFromURL calls the registered creator to create dialers.
2018-03-24 19:57:46 +08:00
func DialerFromURL(s string, dialer Dialer) (Dialer, error) {
u, err := url.Parse(s)
if err != nil {
log.F("parse err: %s", err)
return nil, err
}
2018-03-24 19:57:46 +08:00
if dialer == nil {
dialer = Direct
}
c, ok := dialerMap[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 + "'")
}