Skip to content

Commit 375888a

Browse files
author
Lapp
committed
dockerfile, handler, main, index: fix closing the connection when sending a message from the local host
1 parent 3332c4d commit 375888a

File tree

4 files changed

+8
-2
lines changed

4 files changed

+8
-2
lines changed

Dockerfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ FROM alpine:latest
1111
WORKDIR /opt/
1212

1313
COPY --from=builder /github.com/Lapp-coder/websocket-chat/build/bin/chat .
14+
COPY --from=builder /github.com/Lapp-coder/websocket-chat/index.html .
1415

1516
EXPOSE 8080
1617

handler.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"github.com/gorilla/websocket"
5+
"html/template"
56
"net/http"
67
)
78

@@ -10,6 +11,8 @@ var upgrader = websocket.Upgrader{
1011
WriteBufferSize: 1024,
1112
}
1213

14+
var indexTemplate *template.Template
15+
1316
type handler struct {
1417
hub *hub
1518
}
@@ -24,7 +27,7 @@ func (h *handler) initRoutes() {
2427
}
2528

2629
func (h *handler) index(w http.ResponseWriter, r *http.Request) {
27-
http.ServeFile(w, r, "index.html")
30+
indexTemplate.Execute(w, r.Host)
2831
}
2932

3033
func (h *handler) chat(w http.ResponseWriter, r *http.Request) {

index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
});
2929

3030
if (window["WebSocket"]) {
31-
conn = new WebSocket("ws://localhost:8080/chat");
31+
conn = new WebSocket("ws://{{$}}/chat");
3232
conn.onclose = function(evt) {
3333
appendLog($("<div><b>Соединение закрыто.</b></div>"))
3434
}

main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ package main
33
import (
44
"context"
55
"github.com/sirupsen/logrus"
6+
"html/template"
67
"os"
78
"os/signal"
89
"syscall"
910
)
1011

1112
func main() {
13+
indexTemplate = template.Must(template.ParseFiles("index.html"))
1214
hub := newHub()
1315
handler := newHandler(hub)
1416
handler.initRoutes()

0 commit comments

Comments
 (0)