-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
83 lines (72 loc) · 1.96 KB
/
server.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
package tme
import (
"github.com/dnsge/twitch-mobile-emotes/app"
"github.com/dnsge/twitch-mobile-emotes/emotes"
"github.com/dnsge/twitch-mobile-emotes/storage"
"github.com/go-redis/redis/v8"
"log"
"net/http"
"time"
)
func MakeServer(cfg *app.ServerConfig) *http.Server {
s := &http.Server{
Addr: cfg.Address,
Handler: handleRequest(cfg),
}
go func() {
log.Printf("Starting server on %s\n", cfg.Address)
if err := s.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("listen: %v", err)
}
}()
return s
}
func handleRequest(cfg *app.ServerConfig) http.HandlerFunc {
store := emotes.NewEmoteStore()
if err := store.Init(); err != nil {
log.Fatalln(err)
}
var cache *emotes.ImageFileCache = nil
if cfg.CachePath != "" { // cache is enabled
cache = emotes.NewImageFileCache(cfg.CachePath, time.Hour*48, true)
if err := cache.Index(); err != nil {
log.Fatalln(err)
}
if cfg.Purge {
if err := cache.Purge(); err != nil {
log.Fatalf("Purge cache: %v\n", err)
}
}
go cache.AutoEvict(cfg.Context)
}
var settingsRepository storage.SettingsRepository = nil
if cfg.RedisConn != "" {
opts, err := redis.ParseURL(cfg.RedisConn)
if err != nil {
log.Fatalf("Parse redis URL: %v\n", err)
}
r := storage.NewRedisSettingsRepository(cfg.RedisNamespace, opts, cfg.Context)
if err := r.Ping(); err != nil {
log.Fatalf("Failed to communicate with Redis: %v\n", err)
}
settingsRepository = r
log.Println("Connected to Redis")
}
appCtx := &app.Context{
EmoteStore: store,
ImageCache: cache,
Config: cfg,
SettingsRepository: settingsRepository,
}
manager := NewWsForwarder(appCtx)
return func(w http.ResponseWriter, r *http.Request) {
if r.Host == cfg.WebsocketHost {
manager.HandleWsConnection(w, r)
} else if r.Host == cfg.EmoticonHost {
handleEmoticonRequest(w, r, store, cache)
} else {
log.Printf("Got unexpected Host value %q\n", r.Host)
http.NotFound(w, r)
}
}
}