2018-06-26 16:15:48 +08:00
|
|
|
package proxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2018-10-29 16:18:51 +08:00
|
|
|
"net"
|
2018-06-26 16:15:48 +08:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Server interface
|
|
|
|
type Server interface {
|
2018-11-25 13:18:15 +08:00
|
|
|
// ListenAndServe sets up a listener and serve on it
|
|
|
|
ListenAndServe()
|
|
|
|
|
|
|
|
// Serve serves a connection
|
|
|
|
Serve(c net.Conn)
|
2018-06-26 16:15:48 +08:00
|
|
|
}
|
|
|
|
|
2018-11-25 13:18:15 +08:00
|
|
|
// ServerCreator is a function to create proxy servers
|
2019-09-18 19:40:14 +08:00
|
|
|
type ServerCreator func(s string, proxy Proxy) (Server, error)
|
2018-06-26 16:15:48 +08:00
|
|
|
|
|
|
|
var (
|
2020-09-23 22:14:18 +08:00
|
|
|
serverCreators = make(map[string]ServerCreator)
|
2018-06-26 16:15:48 +08:00
|
|
|
)
|
|
|
|
|
2018-06-26 17:00:13 +08:00
|
|
|
// RegisterServer is used to register a proxy server
|
2018-06-26 16:15:48 +08:00
|
|
|
func RegisterServer(name string, c ServerCreator) {
|
2020-09-27 19:50:21 +08:00
|
|
|
serverCreators[strings.ToLower(name)] = c
|
2018-06-26 16:15:48 +08:00
|
|
|
}
|
|
|
|
|
2018-11-25 13:18:15 +08:00
|
|
|
// ServerFromURL calls the registered creator to create proxy servers
|
|
|
|
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function
|
2019-09-18 19:40:14 +08:00
|
|
|
func ServerFromURL(s string, p Proxy) (Server, error) {
|
|
|
|
if p == nil {
|
2018-08-20 22:23:00 +08:00
|
|
|
return nil, errors.New("ServerFromURL: dialer cannot be nil")
|
|
|
|
}
|
|
|
|
|
2018-06-26 16:15:48 +08:00
|
|
|
if !strings.Contains(s, "://") {
|
|
|
|
s = "mixed://" + s
|
|
|
|
}
|
|
|
|
|
2020-10-23 22:29:12 +08:00
|
|
|
scheme := s[:strings.Index(s, ":")]
|
|
|
|
c, ok := serverCreators[strings.ToLower(scheme)]
|
2018-06-26 16:15:48 +08:00
|
|
|
if ok {
|
2019-09-18 19:40:14 +08:00
|
|
|
return c(s, p)
|
2018-06-26 16:15:48 +08:00
|
|
|
}
|
|
|
|
|
2020-10-23 22:29:12 +08:00
|
|
|
return nil, errors.New("unknown scheme '" + scheme + "'")
|
2018-06-26 16:15:48 +08:00
|
|
|
}
|