2020-04-09 23:09:33 -06:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"golang.org/x/net/websocket"
|
|
|
|
)
|
|
|
|
|
2020-04-12 22:10:12 -06:00
|
|
|
var book Book
|
2020-04-12 20:40:52 -06:00
|
|
|
|
2020-04-09 23:09:33 -06:00
|
|
|
type Client struct {
|
2020-04-12 22:10:12 -06:00
|
|
|
repeaterName string
|
2020-04-09 23:09:33 -06:00
|
|
|
}
|
|
|
|
|
2020-04-12 22:10:12 -06:00
|
|
|
func (c Client) Handle(ws *websocket.Conn) {
|
|
|
|
ws.MaxPayloadBytes = 500
|
|
|
|
book.Join(c.repeaterName, ws)
|
|
|
|
defer book.Part(c.repeaterName, ws)
|
2020-04-09 23:09:33 -06:00
|
|
|
|
2020-04-12 22:10:12 -06:00
|
|
|
for {
|
|
|
|
buf := make([]byte, ws.MaxPayloadBytes)
|
|
|
|
n, err := ws.Read(buf)
|
2020-04-09 23:09:33 -06:00
|
|
|
if err != nil {
|
2020-04-12 22:10:12 -06:00
|
|
|
break
|
2020-04-09 23:09:33 -06:00
|
|
|
}
|
|
|
|
buf = buf[:n]
|
2020-04-12 22:10:12 -06:00
|
|
|
book.Send(c.repeaterName, buf)
|
2020-04-09 23:09:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-12 22:10:12 -06:00
|
|
|
func ChatHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
c := Client {
|
|
|
|
repeaterName: r.FormValue("repeater"),
|
2020-04-09 23:09:33 -06:00
|
|
|
}
|
2020-04-12 22:10:12 -06:00
|
|
|
|
|
|
|
// This API is confusing as hell.
|
|
|
|
// I suspect there's a better way to do this.
|
|
|
|
websocket.Handler(c.Handle).ServeHTTP(w, r)
|
2020-04-09 23:09:33 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2020-04-12 22:10:12 -06:00
|
|
|
book = NewBook()
|
|
|
|
http.Handle("/chat", http.HandlerFunc(ChatHandler))
|
2020-04-09 23:09:33 -06:00
|
|
|
http.Handle("/", http.FileServer(http.Dir("static")))
|
2020-04-12 22:10:12 -06:00
|
|
|
go book.Run()
|
2020-04-09 23:09:33 -06:00
|
|
|
err := http.ListenAndServe(":8080", nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err.Error())
|
|
|
|
}
|
|
|
|
}
|