Skip to content

Commit b94d02d

Browse files
committed
Add docs to chat example
1 parent ba1c24d commit b94d02d

File tree

9 files changed

+31
-2
lines changed

9 files changed

+31
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ go get nhooyr.io/websocket
3434

3535
For a production quality example that demonstrates the complete API, see the [echo example](https://godoc.org/nhooyr.io/websocket#example-package--Echo).
3636

37+
For a full stack example, see the [./example](./example) subdirectory which contains a full chat example.
38+
3739
### Server
3840

3941
```go

example/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Chat Example
2+
3+
This directory contains a full stack example
4+
of a simple chat webapp using nhooyr.io/websocket.
5+
6+
```bash
7+
$ cd example
8+
$ go run .
9+
listening on http://127.0.0.1:51055
10+
```
11+
12+
Visit the printed URL to submit and view broadcasted messages in a browser.
13+
14+
![Image of Example](https://i.imgur.com/iSdpZFT.png)
15+
16+
## Structure
17+
18+
The frontend is contained in `index.html`, `index.js` and `index.css`. It setups the
19+
DOM with a form at the buttom to submit messages and at the top is a scrollable div
20+
that is populated with new messages as they are broadcast. The messages are received
21+
via a WebSocket and messages are published via a POST HTTP endpoint.
22+
23+
The server portion is `main.go` and `chat.go` and implements serving the static frontend
24+
assets as well as the `/subscribe` WebSocket endpoint for subscribing to
25+
broadcast messages and `/publish` for publishing messages.

example-chat/chat.go renamed to example/chat.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@ type chatServer struct {
1818
}
1919

2020
func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) {
21-
println("HELLO")
22-
2321
c, err := websocket.Accept(w, r, nil)
2422
if err != nil {
2523
log.Print(err)
@@ -30,6 +28,10 @@ func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) {
3028
}
3129

3230
func (cs *chatServer) publishHandler(w http.ResponseWriter, r *http.Request) {
31+
if r.Method != "POST" {
32+
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
33+
return
34+
}
3335
body := io.LimitReader(r.Body, 8192)
3436
msg, err := ioutil.ReadAll(body)
3537
if err != nil {
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)