【发布时间】:2019-03-30 23:04:24
【问题描述】:
我对 Go 语言非常陌生,并试图将我的头脑围绕在频道上。为了澄清我的理解,我观看了视频教程,阅读了一些书籍,但在使用 Go 编码的 Web 应用程序中实际编码和使用通道时,我仍然感到困惑。
我想要做的是拥有 2 个 URL:
- 通常的普通 GET 或 POST URL,显示或获取值和 处理它。在后端做了一些处理,我希望 处理输出将在 websocket 更新中发送到相同的 URL,因此不需要刷新/重新加载窗口。
- 一个基于 Gorilla 包的 websockets URL。
以下是迄今为止我尝试过的测试代码,它仍然是我为解决问题而制作的混乱代码的精简版:
//file main.go
package main
import (
"io"
"net/http"
"fmt"
"math/rand"
"log"
"time"
"github.com/gorilla/websocket"
)
func logging(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
if r.URL.Path == `/ws` {
log.Println("WebSocket is accessed from ws://localhost:8080/ws")
}
f(w, r)
}
}
type hotcat int
func (c hotcat) ServeHTTP(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "cat cat cat")
//Some code here who's output I want to pass to websockets url ws://localhost:8080/ws
n := timeConsumingWork(4)
fmt.Println("Random Number Print from cat: ", n)
//Example the value of n I need to pass to ws://localhost:8080/ws, how can I do it?
// Some other example test code just giving some random output from hotcat http handler
// Would like to pass it's output to ws://localhost:8080/ws to print in websocckets output in browser
go func(){
out := make(chan string)
go func(){
for i := 0; ; i++ {
out <- `foo said something`
time.Sleep(time.Duration(rand.Intn(2e3)) * time.Millisecond)
}
//out <- `foo said something`
}()
printer(out)
}()
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Execute this in browser console to initiate websococket connection and to send ws.send() commands etc.
/*
var ws = new WebSocket("ws://localhost:8080/ws")
ws.addEventListener("message", function(e) {console.log(e);});
ws.onmessage = function (event) {
console.log(event.data);
}
ws.send("foo")
ws.send(JSON.stringify({username: "Sat"}))
ws.readyState
ws.CLOSED
ws.OPEN
ws.close()
*/
func ws(w http.ResponseWriter, r *http.Request) {
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
for {
msgType, msg, err := socket.ReadMessage()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(msg))
if err = socket.WriteMessage(msgType, msg); err != nil {
fmt.Println(err)
}
}
}
func main() {
var c hotcat
http.Handle("/cat", c)
http.HandleFunc("/ws", logging(ws))
http.ListenAndServe(":8080", nil)
}
func timeConsumingWork(n int) int {
time.Sleep(time.Microsecond * time.Duration(rand.Intn(500)))
return n + rand.Intn(1000)
}
func printer(in <-chan string) {
//log.Println(<-in)
go func() {
for {
log.Println(<-in)
}
}()
}
# command shell output
$ go run main.go
Random Number Print from cat: 891
2019/03/11 14:15:32 foo said something
2019/03/11 14:15:33 /ws
2019/03/11 14:15:33 WebSocket is accessed from ws://localhost:8080/ws
foo
2019/03/11 14:15:34 foo said something
2019/03/11 14:15:34 foo said something
2019/03/11 14:15:34 foo said something
2019/03/11 14:15:36 foo said something
2019/03/11 14:15:36 foo said something
^Csignal: interrupt
$
我想在浏览器的 websocket 输出中显示随机输出字符串“2019/03/11 14:15:34 foo said something”。
我非常感谢一些指导或帮助。
我认为这个问题的代码、终端输出和浏览器屏幕截图中的 cmets 应该清楚我想要做什么,但如果这个问题仍然不清楚,请告诉我,我会尝试扩展它更多。
感谢和问候,
沙丁鱼
更新 1:
我阅读并尝试了聊天应用程序的 Mat Ryer 示例:https://github.com/matryer/goblueprints/tree/master/chapter1/chat
这是可能的代码副本:https://github.com/satindergrewal/golang-practice/tree/master/chat-examples/mychat02
从示例中我了解到,如果我有一个 web 套接字句柄,我可以将消息从该 websocket http 句柄引导到其他连接的 web 客户端。但是我仍然很困惑如何将消息从非 websocket http 句柄发送到 websocket 句柄路由/地址。
我知道我不能只将此代码用于/ 的ServeHTTP:
// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
fmt.Println(r.Host)
t.templ.Execute(w, r)
var room *room
socket, _ := upgrader.Upgrade(w, r, nil)
client := &client{
socket: socket,
send: make(chan []byte, messageBufferSize),
room: room,
}
room.join <- client
go func() {
for i := 0; i < 10; i++ {
time.Sleep(time.Duration(rand.Intn(8e3)) * time.Millisecond)
client.socket.WriteMessage(websocket.TextMessage, []byte("Hello from / ServeHTTP Handle"))
//fmt.Println("Sending automatic hello from root ServeHTTP handle to web page!")
}
}()
}
它已经给了我以下错误:
localhost:8080
2019/03/25 11:19:18 http: superfluous response.WriteHeader call from github.com/gorilla/websocket.(*Upgrader).returnError (server.go:81)
2019/03/25 11:19:18 http: panic serving [::1]:52691: runtime error: invalid memory address or nil pointer dereference
goroutine 39 [running]:
net/http.(*conn).serve.func1(0xc00013e140)
/usr/local/Cellar/go/1.12.1/libexec/src/net/http/server.go:1769 +0x139
panic(0x13a3e00, 0x172dc20)
/usr/local/Cellar/go/1.12.1/libexec/src/runtime/panic.go:522 +0x1b5
main.(*templateHandler).ServeHTTP(0xc00008ef60, 0x14954a0, 0xc0001dc380, 0xc000214200)
/Users/satinder/go/src/golang-practice/chat-examples/mychat02/main.go:40 +0x209
net/http.(*ServeMux).ServeHTTP(0x173cfa0, 0x14954a0, 0xc0001dc380, 0xc000214200)
/usr/local/Cellar/go/1.12.1/libexec/src/net/http/server.go:2375 +0x1d6
net/http.serverHandler.ServeHTTP(0xc000130000, 0x14954a0, 0xc0001dc380, 0xc000214200)
/usr/local/Cellar/go/1.12.1/libexec/src/net/http/server.go:2774 +0xa8
net/http.(*conn).serve(0xc00013e140, 0x1495ba0, 0xc0000a0380)
/usr/local/Cellar/go/1.12.1/libexec/src/net/http/server.go:1878 +0x851
created by net/http.(*Server).Serve
/usr/local/Cellar/go/1.12.1/libexec/src/net/http/server.go:2884 +0x2f4
更新 2:在再次阅读 cmets 的第一条回复后尝试了不同的方法。
// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
fmt.Println(r.Host)
t.templ.Execute(w, r)
room := newRoom()
go func() {
for i := 0; i < 10; i++ {
time.Sleep(time.Duration(rand.Intn(8e3)) * time.Millisecond)
room.forward <- []byte("Hello from / ServeHTTP Handle")
//client.socket.WriteMessage(websocket.TextMessage, []byte("Hello from / ServeHTTP Handle"))
fmt.Println("Sending automatic hello from root ServeHTTP handle to web page!")
}
}()
}
现在它没有给出错误,但我没有看到控制台显示添加的第二个客户端,我期望通过命令行添加 /。
GoldenBook:mychat02 satinder$ go build -o chat
GoldenBook:mychat02 satinder$ ./chat
2019/03/25 11:37:49 Starting web server on :8080
localhost:8080
New client joined
^C
用以前和新的代码组合再次尝试,结果如下:
// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
fmt.Println(r.Host)
t.templ.Execute(w, r)
room := newRoom()
socket, _ := upgrader.Upgrade(w, r, nil)
client := &client{
socket: socket,
send: make(chan []byte, messageBufferSize),
room: room,
}
room.join <- client
go func() {
for i := 0; i < 10; i++ {
time.Sleep(time.Duration(rand.Intn(8e3)) * time.Millisecond)
room.forward <- []byte("Hello from / ServeHTTP Handle")
//client.socket.WriteMessage(websocket.TextMessage, []byte("Hello from / ServeHTTP Handle"))
//fmt.Println("Sending automatic hello from root ServeHTTP handle to web page!")
}
}()
}
GoldenBook:mychat02 satinder$ go build -o chat
GoldenBook:mychat02 satinder$ ./chat
2019/03/25 11:40:44 Starting web server on :8080
localhost:8080
2019/03/25 11:40:50 http: superfluous response.WriteHeader call from github.com/gorilla/websocket.(*Upgrader).returnError (server.go:81)
^C
仍然感到困惑......
有人可以给我一个解决方案吗?非常感谢您的帮助。
提前致谢。
沙丁鱼
【问题讨论】:
-
谢谢,将尝试理解这个示例的代码并用它来修复我的。如果再次卡住,将更新问题。
-
看到了这个视频,它也解释了同样的概念:youtube.com/watch?v=cNxfgXrHeAg 我没有想过使用自己的类型结构作为通道类型。会玩那个代码。 :-)
-
嗨@CeriseLimón,更新了问题。你能帮忙吗?
-
>从该方法调用 upgrader.Upgrader 失败,因为连接已用于 HTTP 响应。 > 是的,那么我如何在尝试从
/到/room时发送套接字消息? -
:( 很遗憾我无法用代码示例传达我想要做什么。我有一个使用包 webtty 的代码。我使用它的代码来运行仅控制台的应用程序在网页中运行。使用 WebTTY,我将退出 WebTTY 会话并在控制台日志中打印日志输出,我希望将其广播到 websocket。这是我试图解决的练习代码:bit.ly/ 2CGwQAh