Go 通过socks5代理 访问mysql


原文链接: Go 通过socks5代理 访问mysql
//InitDB starts the db connection
func InitDB(c *Config) (*sqlx.DB, error) {
	fmt.Println(c.DBsocks)
	fixieData := strings.Split(c.DBsocks, "@")
	fixieAddr := fixieData[1]
	authData := strings.Split(fixieData[0], ":")
	auth := proxy.Auth{
		User:     authData[0],
		Password: authData[1],
	}

	dialer, err := proxy.SOCKS5("tcp", fixieAddr, &auth, proxy.Direct)
	if err != nil {
		fmt.Fprintln(os.Stderr, "can't connect to the proxy:", err)
		os.Exit(1)
	}

	mysql.RegisterDial("fixieDial", func(addr string) (net.Conn, error) {
		return dialer.Dial("tcp", addr)
	})

	cnx := fmt.Sprintf("%s:%s@fixieDial(%s:3306)/%s?allowOldPasswords=true",
		c.DBuser, c.DBpass, c.DBhost, c.DBname)

	fmt.Println(cnx)

	db, err := sqlx.Connect("mysql", cnx)
	if err != nil {
		fmt.Println("Could not connect")
		log.Fatalln(err)
		return nil, err
	}

	fmt.Println("Connection to db succeed")

	return db, nil
}
`