-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
219 lines (168 loc) · 3.91 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/net/websocket"
)
// TODO: Set to false in production
const debug = true
type templates struct {
*template.Template
}
func (t templates) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.ExecuteTemplate(w, name, data)
}
func initTemplates() templates {
t := template.New("")
t.Funcs(template.FuncMap{
"timeString": func(t time.Time) string {
return t.Format("15:04")
},
})
// parse all html files in the templates directory
t, err := t.ParseGlob("templates/*.html")
if err != nil {
panic(err)
}
return templates{t}
}
// stringRender render a html/template to a string
func stringRender(c echo.Context, name string, data interface{}) string {
b := bytes.NewBuffer(nil)
err := c.Echo().Renderer.Render(b, "message-other-stream", data, c)
if err != nil {
panic(err)
}
return b.String()
}
type Message struct {
Text string
Date time.Time
User string
}
var state struct {
id int
messages map[int]Message
sync.RWMutex
}
func init() {
state.messages = make(map[int]Message)
}
func addMiddleware(e *echo.Echo) {
if debug {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "method=${method}, uri=${uri}, status=${status}, latency_human=${latency_human}\n",
}))
}
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
e.Use(middleware.Gzip(), middleware.Secure())
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
TokenLookup: "form:csrf",
}))
}
func routes(e *echo.Echo) {
e.Static("/dist", "./dist")
e.GET("/", root)
e.GET("/recieve", recieveMessages)
e.POST("/send", sendMessage)
}
func main() {
e := echo.New()
e.Debug = debug
e.Renderer = initTemplates()
addMiddleware(e)
routes(e)
e.Start(":3000")
}
func root(c echo.Context) error {
sess, _ := session.Get("session", c)
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
if sess.Values["user"] == nil {
sess.Values["user"] = uuid.New().String()
}
sess.Save(c.Request(), c.Response())
state.RLock()
defer state.RUnlock()
return c.Render(200, "index.html", map[string]interface{}{
"title": "Chat",
"messages": state.messages,
"user": userID(c),
"csrf": csrfToken(c),
})
}
func sendMessage(c echo.Context) error {
msg := c.FormValue("message")
if msg == "" {
return fmt.Errorf("empty message not allowed")
}
state.Lock()
defer state.Unlock()
state.id++
message := Message{
Text: msg,
Date: time.Now(),
User: userID(c),
}
state.messages[state.id] = message
if isTurbo(c) {
return c.Render(200, "message-self-stream", message)
}
return root(c)
}
func userID(c echo.Context) string {
sess, _ := session.Get("session", c)
return sess.Values["user"].(string)
}
func recieveMessages(c echo.Context) error {
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
state.RLock()
lastid := state.id
state.RUnlock()
for {
func() {
state.RLock()
defer state.RUnlock()
if state.id == lastid {
return
}
lastid = state.id
msg := state.messages[state.id]
if msg.User == userID(c) {
return
}
rMsg := stringRender(c, "message-other-stream", msg)
websocket.Message.Send(ws, rMsg)
}()
time.Sleep(1 * time.Millisecond)
}
}).ServeHTTP(c.Response(), c.Request())
return nil
}
func csrfToken(c echo.Context) string {
return c.Get("csrf").(string)
}
func isTurbo(c echo.Context) bool {
accept := c.Request().Header.Get("Accept")
if !strings.Contains(accept, "text/vnd.turbo-stream.html") {
return false
}
c.Response().Header().Set("Content-Type", "text/vnd.turbo-stream.html")
return true
}