douwengzao5790 2014-02-28 09:39
浏览 67
已采纳

无法让go.net/websocket在Nginx后面运行

I'm having trouble getting go.net/websocket to work behind nginx. It works if the application is accessed directly but with nginx, I get an EOF error from Receive.

What am I doing wrong?

Nginx version: 1.5.10

This is my nginx configuration.

location /wstest/ {
    proxy_pass http://localhost:7415/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade "websocket";
    proxy_set_header Connection "Upgrade";
    proxy_buffering off;
}

Go code:

func main() {
    http.HandleFunc("/", home)
    http.Handle("/sock", websocket.Handler(pingpong))

    http.ListenAndServe(":7415", nil)
}

func home(w http.ResponseWriter, r *http.Request) {
    homeTmpl.Execute(w, nil)
}

func pingpong(conn *websocket.Conn) {
    var msg string
    if err := websocket.Message.Receive(conn, &msg); err != nil {
        log.Println("Error while receiving message:", err)
        return
    }

    if msg == "ping" {
        websocket.Message.Send(conn, "pong")
    }
}

var homeTmpl = template.Must(template.New("home").Parse(`
<!doctype html>
<html>
<head>
<title>WS Test</title>
<script>
    var path = window.location.pathname;
    var wsURL = "ws://" + window.location.host +  path.substring(0,   path.lastIndexOf('/')) + "/sock";
    var ws;

    document.addEventListener("DOMContentLoaded", function() {
        ws = new WebSocket(wsURL);
        ws.onopen = function() {
        ws.send("ping");
    };

    ws.onmessage = function(event) {
        document.getElementById("status").innerHTML = "Received: " + String(event.data);
    };
})
</script>
</head>
<body>
<span id="status">Pinging...</span>
</body>
</html>`))
  • 写回答

1条回答 默认 最新

  • dongqi0644 2014-03-03 23:01
    关注

    This is the configuration that I'm using, it's working OK:

    server {
        listen 0.0.0.0:20007;    
        index index.html;
    
         root /full/path/to/site;
    
        # pass the request to the node.js server with the correct headers 
        location / {
    
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_set_header X-NginX-Proxy true;
    
          proxy_pass http://your_app/;
          proxy_redirect off;
    
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
        }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)