-
-
Notifications
You must be signed in to change notification settings - Fork 457
/
main.go
47 lines (40 loc) · 1018 Bytes
/
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
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://docs.gofiber.io
// 📝 Github Repository: https://github.com/gofiber/fiber
package main
import (
"fmt"
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/websocket"
)
func main() {
app := fiber.New()
// Optional middleware
app.Use("/ws", func(c *fiber.Ctx) error {
if c.Get("host") == "localhost:3000" {
c.Locals("Host", "Localhost:3000")
return c.Next()
}
return c.Status(403).SendString("Request origin not allowed")
})
// Upgraded websocket request
app.Get("/ws", websocket.New(func(c *websocket.Conn) {
fmt.Println(c.Locals("Host")) // "Localhost:3000"
for {
mt, msg, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
err = c.WriteMessage(mt, msg)
if err != nil {
log.Println("write:", err)
break
}
}
}))
// ws://localhost:3000/ws
log.Fatal(app.Listen(":3000"))
}