mirror of
https://github.com/nadoo/glider.git
synced 2025-02-23 09:25:41 +08:00
57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package proxy
|
|
|
|
import (
|
|
"errors"
|
|
"net"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/nadoo/glider/common/log"
|
|
)
|
|
|
|
// Server interface
|
|
type Server interface {
|
|
// ListenAndServe sets up a listener and serve on it
|
|
ListenAndServe()
|
|
|
|
// Serve serves a connection
|
|
Serve(c net.Conn)
|
|
}
|
|
|
|
// ServerCreator is a function to create proxy servers
|
|
type ServerCreator func(s string, proxy Proxy) (Server, error)
|
|
|
|
var (
|
|
serverCreators = make(map[string]ServerCreator)
|
|
)
|
|
|
|
// RegisterServer is used to register a proxy server
|
|
func RegisterServer(name string, c ServerCreator) {
|
|
serverCreators[name] = c
|
|
}
|
|
|
|
// 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
|
|
func ServerFromURL(s string, p Proxy) (Server, error) {
|
|
if p == nil {
|
|
return nil, errors.New("ServerFromURL: dialer cannot be nil")
|
|
}
|
|
|
|
if !strings.Contains(s, "://") {
|
|
s = "mixed://" + s
|
|
}
|
|
|
|
u, err := url.Parse(s)
|
|
if err != nil {
|
|
log.F("parse err: %s", err)
|
|
return nil, err
|
|
}
|
|
|
|
c, ok := serverCreators[strings.ToLower(u.Scheme)]
|
|
if ok {
|
|
return c(s, p)
|
|
}
|
|
|
|
return nil, errors.New("unknown scheme '" + u.Scheme + "'")
|
|
}
|