-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
96 lines (77 loc) · 2.09 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
package main
import (
"log"
"net/http"
"os"
"github.com/caddyserver/certmagic"
"github.com/go-redis/redis"
socketio "github.com/googollee/go-socket.io"
"github.com/xenolf/lego/providers/dns/cloudflare"
)
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
func main() {
// check RTHOST environment variable
rthost := getEnv("RTHOST", "")
if rthost == "" {
log.Fatalln("Please set RTHOST to domain to request certificate for")
}
// redis connection
client := redis.NewClient(&redis.Options{
Addr: getEnv("REDISHOST", "localhost:6379"),
})
// subscribe to all channels
pubsub := client.PSubscribe("*")
_, err := pubsub.Receive()
if err != nil {
panic(err)
}
// messages received on a Go channel
ch := pubsub.Channel()
// ping Redis server
pong, err := client.Ping().Result()
log.Println(pong, err)
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
log.Printf("New connection from %s ", so.Id())
// listen from channel message from client and join client to the channel name
so.On("channel", func(channel string) {
log.Printf("%s joins channel %s\n", so.Id(), channel)
so.Join(channel)
so.BroadcastTo(channel, "hello")
})
so.On("disconnection", func() {
log.Printf("disconnect from %s\n", so.Id())
})
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
// Consume messages from Redis
go func(srv *socketio.Server) {
for msg := range ch {
log.Println(msg.Channel, msg.Payload)
srv.BroadcastTo(msg.Channel, "message", msg.Payload)
}
}(server)
// certificate magic
certmagic.DefaultACME.Agreed = true
certmagic.DefaultACME.CA = certmagic.LetsEncryptStagingCA
cloudflare, err := cloudflare.NewDNSProvider()
if err != nil {
log.Fatal(err)
}
certmagic.DefaultACME.DNSProvider = cloudflare
mux := http.NewServeMux()
mux.Handle("/socket.io/", server)
mux.Handle("/", http.FileServer(http.Dir("./assets")))
certmagic.HTTPS([]string{rthost}, mux)
}