Featured image of post gorilla/websocket 客户端报错Forbidden

gorilla/websocket 客户端报错Forbidden

问题描述

在使用golangwebsocket服务时,不可避免需要使用gorilla/websocket包.

在官方提供的example示例中,监听的ip都是localhost, 但是当需要对外提供服务时, 我们需要把ip改为0.0.0.0或者具体的ip。 此时如果使用gorilla/websocket包写客户端的话,使用默认的DefaultDialer去连接具体的ip, 客户端报错Forbidden

解决办法

通过查看gorilla/websocket包源码, 发现DefaultDialer的结构为

1
2
3
4
var DefaultDialer = &Dialer{
	Proxy:            http.ProxyFromEnvironment,
	HandshakeTimeout: 45 * time.Second,
}

ProxyFromEnvironment函数会读取环境变量里的http_proxyhttps_proxy代理, 我的测试环境是设置了代理,所以会报错。

解决方法是不使用DefaultDialer,而是使用Dialer结构体.

1
2
3
4
5
6
dialer := websocket.Dialer{
	ReadBufferSize:   2048,
	WriteBufferSize:  2048,
	HandshakeTimeout: 45 * time.Second,
}
dialer.Dial("ws://127.0.0.1:8080/ws", nil)
本博客已稳定运行
发表了28篇文章 · 总计46.73k字
本站总访问量 次 · 您是本站第 位访问者
粤ICP备2025368587号-1| 使用 Hugo 构建
主题 StackJimmy 设计