Skip to content

Commit 3332c4d

Browse files
author
Lapp
committed
project: client part is implemented. handler: added handler to work with the client
1 parent 7658b7e commit 3332c4d

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

handler.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,14 @@ func newHandler(hub *hub) *handler {
1919
}
2020

2121
func (h *handler) initRoutes() {
22+
http.HandleFunc("/", h.index)
2223
http.HandleFunc("/chat", h.chat)
2324
}
2425

26+
func (h *handler) index(w http.ResponseWriter, r *http.Request) {
27+
http.ServeFile(w, r, "index.html")
28+
}
29+
2530
func (h *handler) chat(w http.ResponseWriter, r *http.Request) {
2631
ws, err := upgrader.Upgrade(w, r, nil)
2732
if err != nil {

index.html

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<title>Чат</title>
5+
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
6+
<script type="text/javascript">
7+
$(function() {
8+
var conn;
9+
var msg = $("#msg");
10+
var log = $("#log");
11+
12+
function appendLog(msg) {
13+
var d = log[0]
14+
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
15+
msg.appendTo(log)
16+
if (doScroll) {
17+
d.scrollTop = d.scrollHeight - d.clientHeight;
18+
}
19+
}
20+
21+
$("#form").submit(function() {
22+
if (!conn || !msg.val()) {
23+
return false;
24+
}
25+
conn.send(msg.val());
26+
msg.val("");
27+
return false
28+
});
29+
30+
if (window["WebSocket"]) {
31+
conn = new WebSocket("ws://localhost:8080/chat");
32+
conn.onclose = function(evt) {
33+
appendLog($("<div><b>Соединение закрыто.</b></div>"))
34+
}
35+
conn.onmessage = function(evt) {
36+
appendLog($("<div/>").text(evt.data))
37+
}
38+
} else {
39+
appendLog($("<div><b>Ваш браузер не поддерживает вебсокеты.</b></div>"))
40+
}
41+
});
42+
</script>
43+
<style>
44+
html {
45+
overflow: hidden;
46+
}
47+
48+
body {
49+
overflow: hidden;
50+
padding: 0;
51+
margin: 0;
52+
width: 100%;
53+
height: 100%;
54+
background: gray;
55+
}
56+
57+
#log {
58+
background: white;
59+
margin: 0;
60+
padding: 0.5em 0.5em 0.5em 0.5em;
61+
position: absolute;
62+
top: 0.5em;
63+
left: 0.5em;
64+
right: 0.5em;
65+
bottom: 3em;
66+
overflow: auto;
67+
}
68+
69+
#form {
70+
padding: 0 0.5em 0 0.5em;
71+
margin: 0;
72+
position: absolute;
73+
bottom: 1em;
74+
left: 0px;
75+
width: 100%;
76+
overflow: hidden;
77+
}
78+
79+
</style>
80+
</head>
81+
<body>
82+
<div id="log"></div>
83+
<form id="form">
84+
<input type="submit" value="Send" />
85+
<input type="text" id="msg" size="64"/>
86+
</form>
87+
</body>
88+
</html>

0 commit comments

Comments
 (0)