1.挺好用的socks5庫
2.示例代碼
// Create a SOCKS5 server
conf := &socks5.Config{}
server, err := socks5.New(conf)
if err != nil {
panic(err)
}
// Create SOCKS5 proxy on localhost port 8000
if err := server.ListenAndServe("tcp", "127.0.0.1:8000"); err != nil {
panic(err)
}
很簡潔,當然正式用不能這么用,默認是沒有認證的,也就是說所有人都能連你服務器。。
加認證也很簡單
cred := StaticCredentials{
"foo": "bar",
}
cator := UserPassAuthenticator{Credentials: cred}
s, _ := New(&Config{AuthMethods: []Authenticator{cator}})
下面詳細看一下這個認證
Config結構體:
// Config is used to setup and configure a Server
type Config struct {
// AuthMethods can be provided to implement custom authentication
// By default, "auth-less" mode is enabled.
// For password-based auth use UserPassAuthenticator.
AuthMethods []Authenticator
// If provided, username/password authentication is enabled,
// by appending a UserPassAuthenticator to AuthMethods. If not provided,
// and AUthMethods is nil, then "auth-less" mode is enabled.
Credentials CredentialStore
// Resolver can be provided to do custom name resolution.
// Defaults to DNSResolver if not provided.
Resolver NameResolver
// Rules is provided to enable custom logic around permitting
// various commands. If not provided, PermitAll is used.
Rules RuleSet
// Rewriter can be used to transparently rewrite addresses.
// This is invoked before the RuleSet is invoked.
// Defaults to NoRewrite.
Rewriter AddressRewriter
// BindIP is used for bind or udp associate
BindIP net.IP
// Logger can be used to provide a custom log target.
// Defaults to stdout.
Logger *log.Logger
// Optional function for dialing out
Dial func(ctx context.Context, network, addr string) (net.Conn, error)
}
config結構體里面要傳入AuthMethods
AuthMethods是一個Authenticator切片,Authenticator是個interface,
type Authenticator interface {
Authenticate(reader io.Reader, writer io.Writer) (*AuthContext, error)
GetCode() uint8
}
UserPassAuthenticator 實現了Authenticator
// UserPassAuthenticator is used to handle username/password based
// authentication
type UserPassAuthenticator struct {
Credentials CredentialStore
}
func (a UserPassAuthenticator) GetCode() uint8 {
return UserPassAuth
}
最后轉化為填充一個UserPassAuthenticator的Credentials ,
而Credentials 是一個map[string]string
type StaticCredentials map[string]string
最后要把Config里面的logger 字段給填了(這里略),就差不多能用了。
3. 適用場景
適用移動網絡訪問github慢的場景。不知道為啥移動上github總是很慢。在公司電信網絡就很快,之前家里用聯通的時候也沒這個現象,我上github你限制我干嗎。。用此socks配合瀏覽器插件foxyProxy繞過移動網絡直連github效果明顯。注意foxyProxy里面設置Patterns ,不然什么請求到服務器上繞一圈可是有點過了。。