This should be straight forward.
(这应该很简单。)
I have looked at all the examples I can find on the web and think my code is right.(我看了所有可以在网上找到的示例,并认为我的代码是正确的。)
But when I send two strings in a JSON variable from JavaScript to a Go web server via a websocket, all I ever get is: msg = {}.(但是,当我通过websocket将两个JSON变量中的字符串从JavaScript发送到Go Web服务器时,我得到的只是:msg = {}。)
Please let me know what I am doing wrong.(请让我知道我在做什么错。)
Thanks.(谢谢。)
HTML:(HTML:)
Foo: <input id="fooIn" type="text" />
Bar: <input id="BarIn" type="text" />
<button onclick="Send()">Send</button>
<script>
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function (event) {
output.innerHTML += "Server: " + event.data + "
";
};
function Send() {
var wsObj = {foo:document.getElementById("fooIn").value,
bar:document.getElementById("BarIn").value};
socket.send(JSON.stringify(wsObj));
};
</script>
Go:
(走:)
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
type fooBar struct {
foo string `json:"foo"`
bar string `json:"bar"`
}
var upgrader = websocket.Upgrader{}
func main() {
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
ws, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity
defer ws.Close()
var msg fooBar
for {
err := ws.ReadJSON(&msg)
if err != nil {
log.Fatal("ReadJSON error: ", err)
}
log.Print("Got: ", msg, " Foo: ", msg.foo, " Bar: ", msg.bar)
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html")
})
fmt.Print("Running Server on :8080.
")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}```
ask by John Layne translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…