-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.go
99 lines (85 loc) · 1.83 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
"github.com/alfred-zhong/wserver"
"github.com/google/uuid"
)
func main() {
port := 12345
userID := uuid.New().String()
event := "alarm"
// run wserver
go func() {
s := wserver.NewServer(":" + strconv.Itoa(port))
if err := s.ListenAndServe(); err != nil {
log.Fatalln(err)
}
}()
// run http server
go func() {
httpPort := 8081
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tplName := "index.html"
t, err := template.ParseFiles(tplName)
if err != nil {
log.Printf("template[%s] parse fail: %v", tplName, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
t.Execute(w, struct {
Port int
Token string
Event string
}{
port,
userID,
event,
})
})
log.Printf("open url: http://localhost:%d", httpPort)
if err := http.ListenAndServe(":"+strconv.Itoa(httpPort), nil); err != nil {
log.Fatalln(err)
}
}()
time.Sleep(time.Second)
// send messages in loop
url := fmt.Sprintf("http://localhost:%d/send", port)
for {
msg := msg{
UserID: userID,
Event: event,
Message: fmt.Sprintf("hello -- %d", rand.Int()),
}
sendMsg(msg, url)
time.Sleep(10 * time.Millisecond)
}
}
type msg struct {
UserID string `json:"userId"`
Event string `json:"event"`
Message string `json:"message"`
}
func (m msg) String() string {
bb, _ := json.Marshal(m)
return string(bb)
}
func sendMsg(m msg, url string) {
res, err := http.DefaultClient.Post(url, "application/json", strings.NewReader(m.String()))
if err != nil {
log.Printf("send message fail: %v", err)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("status code: %d not expected", res.StatusCode)
return
}
}