这个websocket url“ws:// {{$}} / ws”是什么意思?

时间:2013-08-17 16:14:35

标签: url websocket go

我在使用websocket工作。我从一个简单的例子中获得了一个websocket url格式,我想这样:

ws://{{$}}/ws

以下相对完整的代码:

home.html的:

<html>
<head>
<title>Chat Example</title>
<script type="text/javascript">
    $(function() {
        ......
        if (window["WebSocket"]) {
            conn = new WebSocket("ws://{{$}}/ws");
            conn.onclose = function(evt) {
                appendLog($("<div><b>Connection closed.</b></div>"))
            }
            conn.onmessage = function(evt) {
                appendLog($("<div/>").text(evt.data))
            }
        } else {
            appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
        }
        ......
    });
</script>
</head>
</html>

和wsServer.go:

package main

import (
    "flag"
    "log"
    "net/http"
    "text/template"
)
var addr = flag.String("addr", ":8080", "http service address")
var homeTempl = template.Must(template.ParseFiles("home.html"))

func serveHome(w http.ResponseWriter, r *http.Request) {
    ......
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    homeTempl.Execute(w, r.Host)
}

func main() {
    http.HandleFunc("/", serveHome)
    http.HandleFunc("/ws", serveWs)
    err := http.ListenAndServe(:8080, nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

我认为这是一个正则表达式,而实际上我无法解释它。

我在自己的PC浏览器上测试它,并将成功与:

连接起来
http://localhost:8080 

但是

http://ip:8080 (which ip is my computer's also the litsening server's ip)

不。 为什么?

当我将“ws:// {{$}} / ws”更改为某个网址时,它会起作用。但我想知道为什么?这个表达式可以匹配什么?

完整的示例代码很大,我认为上面的问题已经足够了。如果我遗漏了一些内容,您可以在此页面中找到完整示例:https://github.com/garyburd/go-websocket/tree/master/examples/chat

1 个答案:

答案 0 :(得分:1)

我猜你正在使用Go的template包。模板包支持由这些大括号注释的{{ placeholders }}。这些大括号可能包含rangeif等语句和变量名称。变量名$是一个特殊名称,指向传递给template.Execute方法的根元素。

请添加wsServe方法的代码,以便我们可以看到您传递给模板的价值。我会在之后扩展我的答案。

相关问题