good morning!!!!

Skip to content
Snippets Groups Projects
Unverified Commit bdae16ee authored by Anmol Sethi's avatar Anmol Sethi
Browse files

Add docs to chat example

parent ba1c24d1
Branches
Tags
No related merge requests found
...@@ -34,6 +34,8 @@ go get nhooyr.io/websocket ...@@ -34,6 +34,8 @@ go get nhooyr.io/websocket
For a production quality example that demonstrates the complete API, see the [echo example](https://godoc.org/nhooyr.io/websocket#example-package--Echo). For a production quality example that demonstrates the complete API, see the [echo example](https://godoc.org/nhooyr.io/websocket#example-package--Echo).
For a full stack example, see the [./example](./example) subdirectory which contains a full chat example.
### Server ### Server
```go ```go
......
# Chat Example
This directory contains a full stack example
of a simple chat webapp using nhooyr.io/websocket.
```bash
$ cd example
$ go run .
listening on http://127.0.0.1:51055
```
Visit the printed URL to submit and view broadcasted messages in a browser.
![Image of Example](https://i.imgur.com/iSdpZFT.png)
## Structure
The frontend is contained in `index.html`, `index.js` and `index.css`. It setups the
DOM with a form at the buttom to submit messages and at the top is a scrollable div
that is populated with new messages as they are broadcast. The messages are received
via a WebSocket and messages are published via a POST HTTP endpoint.
The server portion is `main.go` and `chat.go` and implements serving the static frontend
assets as well as the `/subscribe` WebSocket endpoint for subscribing to
broadcast messages and `/publish` for publishing messages.
...@@ -18,8 +18,6 @@ type chatServer struct { ...@@ -18,8 +18,6 @@ type chatServer struct {
} }
func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) { func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) {
println("HELLO")
c, err := websocket.Accept(w, r, nil) c, err := websocket.Accept(w, r, nil)
if err != nil { if err != nil {
log.Print(err) log.Print(err)
...@@ -30,6 +28,10 @@ func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) { ...@@ -30,6 +28,10 @@ func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) {
} }
func (cs *chatServer) publishHandler(w http.ResponseWriter, r *http.Request) { func (cs *chatServer) publishHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
body := io.LimitReader(r.Body, 8192) body := io.LimitReader(r.Body, 8192)
msg, err := ioutil.ReadAll(body) msg, err := ioutil.ReadAll(body)
if err != nil { if err != nil {
......
File moved
File moved
File moved
File moved
;(() => { ;(() => {
let conn let conn
let submitted = false let expectingMessage = false
function dial() { function dial() {
conn = new WebSocket(`ws://${location.host}/subscribe`) conn = new WebSocket(`ws://${location.host}/subscribe`)
conn.addEventListener("close", () => { conn.addEventListener("close", (ev) => {
conn = undefined console.error("subscribe WebSocket closed", ev)
console.info("reconnecting in 1000ms", ev)
setTimeout(dial, 1000) setTimeout(dial, 1000)
}) })
conn.addEventListener("message", ev => { conn.addEventListener("message", ev => {
if (typeof ev.data !== "string") { if (typeof ev.data !== "string") {
console.error("unexpected message type", typeof ev.data)
return return
} }
appendLog(ev.data) appendLog(ev.data)
if (submitted) { if (expectingMessage) {
messageLog.scrollTo(0, messageLog.scrollHeight) messageLog.scrollTo(0, messageLog.scrollHeight)
submitted = false expectingMessage = false
} }
}) })
return conn
} }
dial() dial()
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
} }
appendLog("Submit a message to get started!") appendLog("Submit a message to get started!")
publishForm.onsubmit = ev => { publishForm.onsubmit = async ev => {
ev.preventDefault() ev.preventDefault()
const msg = messageInput.value const msg = messageInput.value
...@@ -43,10 +43,12 @@ ...@@ -43,10 +43,12 @@
} }
messageInput.value = "" messageInput.value = ""
submitted = true expectingMessage = true
fetch("/publish", { fetch("/publish", {
method: "POST", method: "POST",
body: msg, body: msg,
}).catch(err => {
console.error("failed to publish", err)
}) })
} }
})() })()
File moved
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment