Golang连接Rabbitmq账号或密码中有特殊字符报错

Golang连接Rabbitmq一般使用github.com/streadway/amqp这个库,简单的使用方法如下:

package main
import (
    "fmt"
    "github.com/streadway/amqp"
)
func main() {
    host := "127.0.0.1"
    port := "5672"
    vhost := "test"
    user := "test"
    password := "test"
    amqpconf := amqp.Config{
        Vhost:     vhost,
        Heartbeat: 10 * time.Second,
        Locale:    "en_US",
    }
    conn, err := amqp.DialConfig(fmt.Sprintf("amqp://%s:%s@%s:%s/", user, password, host, port), amqpcoinf)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(conn)
}

但是当用户名或密码有特殊字符(例如 @#)时就会报错,解决方法就是将特殊字符进行转义,方法如下:

user := url.QueryEscape(user)
password := url.QueryEscape(password)

实例如下:

package main
import (
    "fmt"
    "net/url"
    "github.com/streadway/amqp"
)
func main() {
    host := "127.0.0.1"
    port := "5672"
    vhost := "test"
    //假如用户名为 test@test.com
    user := url.QueryEscape("test@test.com")
    //假如密码为 test#pwd
    password := url.QueryEscape("test#pwd")
    amqpconf := amqp.Config{
        Vhost:     vhost,
        Heartbeat: 10 * time.Second,
        Locale:    "en_US",
    }
    conn, err := amqp.DialConfig(fmt.Sprintf("amqp://%s:%s@%s:%s/", user, password, host, port), amqpcoinf)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(conn)
}
微信公众号
关注36nu微信公众账号
获取最新编程知识及经验