使用Go通过WebSocket流式获取Mastodon公开帖子时遭遇bad handshake错误的解决方案咨询
使用Go通过WebSocket流式获取Mastodon公开帖子时遭遇bad handshake错误的解决方案咨询
最近我在尝试用WebSocket实时流式获取Mastodon的公开帖子,用HTTP API获取公开帖子的功能完全正常,但WebSocket连接一直抛出websocket: bad handshake错误,想请教各位有没有遇到过类似问题,或者我是不是遗漏了什么配置步骤?
我使用的WebSocket URL
一开始我直接用这个URL连接mastodon.social的公开时间线流:
wss://mastodon.social/api/v1/streaming/public
但每次连接都会报错websocket: bad handshake。
用websocat验证环境
为了排除本地环境的问题,我先用websocat测试了一个通用的WebSocket echo服务:
websocat wss://echo.websocket.org
这个测试完全正常,能正常发送并收到返回消息,说明我的WebSocket客户端环境本身是没问题的。
HTTP API测试正常
我同时测试了Mastodon的HTTP API接口,获取公开时间线的功能完全正常:
curl https://mastodon.social/api/v1/timelines/public
能成功拿到完整的公开帖子列表,说明我访问Mastodon实例的网络和权限是没问题的。
我的Go代码实现
我用Go语言结合gorilla/websocket库写了测试代码,具体如下:
package main import ( "fmt" "log" "os" "github.com/gorilla/websocket" ) func streamPublicTimelineWebSocket(instanceURL string) { // Updated Mastodon Streaming WebSocket API URL for public posts url := fmt.Sprintf("wss://%s/api/v1/streaming/public", instanceURL) // Create a WebSocket dialer to manage the connection dialer := websocket.DefaultDialer // Create a map for custom headers if necessary (e.g., User-Agent) headers := map[string][]string{ "User-Agent": {"Mastodon Streamer Go"}, } // Establish a WebSocket connection with custom headers conn, _, err := dialer.Dial(url, headers) if err != nil { log.Fatalf("Failed to connect to Mastodon streaming WebSocket: %v", err) os.Exit(1) } defer conn.Close() log.Printf("Successfully connected to stream at: %s", url) // Continuously read and process incoming WebSocket messages for { _, msg, err := conn.ReadMessage() if err != nil { log.Fatalf("Error reading WebSocket message: %v", err) } // Print out the received message (which is a Mastodon post) log.Printf("Received message: %s", msg) } } func main() { // Replace with your Mastodon instance URL (e.g., "streaming.mastodon.social") instanceURL := "streaming.mastodon.social" // Updated to the correct WebSocket URL // Start streaming the public timeline in real-time using WebSocket log.Println("Starting streaming from Mastodon...") streamPublicTimelineWebSocket(instanceURL) }
备注:内容来源于stack exchange,提问作者Europa
相关产品推荐
相关产品推荐

