-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (68 loc) · 1.66 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
package main
import (
"embed"
"fmt"
"github.com/nidorx/chain"
"github.com/nidorx/chain/socket"
"log"
"net/http"
"os"
"strings"
)
var (
//go:embed public
staticFiles embed.FS
staticDir = "public"
)
func main() {
// Used by session
if err := chain.SetSecretKeyBase("ZcbD0D29eYsGq89QjirJbPkw7Qxwxboy"); err != nil {
panic(err)
}
router := chain.New()
var staticFS = http.FS(staticFiles)
fs := rootPath(http.FileServer(staticFS))
router.GET("/*", fs)
router.Configure("/socket", AppSocket)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Listening on :%s...\n", port)
if err := http.ListenAndServe(fmt.Sprintf(":%s", port), router); err != nil {
log.Fatalf("ListenAndServe: %v", err)
}
}
func rootPath(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
r.URL.Path = fmt.Sprintf("/%s/", staticDir)
} else {
b := strings.Split(r.URL.Path, "/")[0]
if b != staticDir {
r.URL.Path = fmt.Sprintf("/%s%s", staticDir, r.URL.Path)
}
}
h.ServeHTTP(w, r)
})
}
var AppSocket = &socket.Handler{
Channels: []*socket.Channel{
socket.NewChannel("chat:*", chatChannel),
},
OnConfig: func(handler *socket.Handler, router *chain.Router, endpoint string) error {
return nil
},
OnConnect: func(info *socket.Session) error {
return nil
},
}
func chatChannel(channel *socket.Channel) {
channel.Join("chat:lobby", func(_ any, _ *socket.Socket) (reply any, err error) {
return
})
channel.HandleIn("shout", func(event string, payload any, socket *socket.Socket) (reply any, err error) {
err = socket.Broadcast("shout", payload)
return
})
}