【问题标题】:Unable to get go.net/websocket working behind nginx无法让 go.net/websocket 在 nginx 后面工作
【发布时间】:2014-04-01 05:31:38
【问题描述】:

我无法让 go.net/websocket 在 nginx 后面工作。如果直接访问应用程序但使用 nginx,则它可以工作,我从 Receive 收到 EOF 错误。

我做错了什么?

Nginx 版本:1.5.10

这是我的 nginx 配置。

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;
}

转码:

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>`))

【问题讨论】:

标签: nginx websocket go


【解决方案1】:

这是我正在使用的配置,它工作正常:

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";
    }
 }

【讨论】:

  • proxy_set_header Upgrade "websocket"; 更改为proxy_set_header Upgrade $http_upgrade; 有效。
  • 谢谢,设置 proxy_set_header Host $http_host; 对我有帮助。为什么不在配置websockets代理的nginx示例上?
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 2021-08-11
  • 2012-05-14
  • 2011-09-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2016-02-22
相关资源
最近更新 更多