-
Notifications
You must be signed in to change notification settings - Fork 4
/
example.go
74 lines (62 loc) · 1.47 KB
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/DATA-DOG/golang-websocket-hub"
)
var TokenSecret = "secret-hash-code"
type Application struct {
hub.Hub
}
func New() *Application {
app := &Application{
Hub: *hub.New(os.Stdout, "*"),
}
app.SubscriptionTokenizer = hub.HmacSha256Tokenizer(TokenSecret)
return app
}
func (app *Application) asset(path string) {
http.HandleFunc("/"+path, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, path)
})
}
func (app *Application) index() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "example.html")
})
}
func (app *Application) message() {
http.HandleFunc("/message", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var msg hub.Message
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
to := r.URL.Query().Get("to")
if len(to) > 0 {
app.Mailbox <- &hub.MailMessage{
Message: &msg,
Username: to,
}
} else {
app.Broadcast <- &msg
}
})
}
func main() {
app := New()
app.asset("example.css")
app.asset("example.js")
app.message()
app.index()
go app.Run()
http.Handle("/ws", app)
log.Println("listening on: http://localhost:8000")
log.Fatal(http.ListenAndServe(":8000", nil))
}