/
hakobiya.go
86 lines (76 loc) · 1.88 KB
/
hakobiya.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
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"unicode/utf8"
"code.google.com/p/go.net/websocket"
)
var configFile = flag.String("config", "config.toml", "config file path")
var currentConfig config
var templates = make(map[rune]channelTemplate)
func main() {
flag.Parse()
// load config
cfg, ok := parseConfig(*configFile)
if !ok {
log.Println("Bad config file, giving up.")
return
}
currentConfig = cfg
channelBanner := ""
for _, tmpl := range cfg.Channels {
channelBanner += tmpl.Prefix
prefix, _ := utf8.DecodeRuneInString(tmpl.Prefix)
templates[prefix] = tmpl
}
// start http services
log.Printf("Hakobiya: Starting %s @ %s%s", cfg.Server.Name, cfg.Server.Bind, cfg.Server.Path)
log.Printf("Channels (%d): %s", len(templates), channelBanner)
http.Handle(cfg.Server.Path, websocket.Handler(serveWS))
// api
if cfg.API.Enabled {
apiPath := cfg.API.Path
http.Handle(apiPath+"/", apiHandler(cfg.API))
log.Printf("API: enabled at %s/", apiPath)
} else {
log.Printf("API: off")
}
// static server
if cfg.Static.Enabled {
log.Printf("Static content server: enabled")
if cfg.Static.Index == "" {
http.HandleFunc("/", http.NotFound)
} else {
http.HandleFunc("/", index)
log.Printf("Serving: / → %s", cfg.Static.Index)
}
for _, dir := range cfg.Static.Dirs {
path := "/" + filepath.Base(dir) + "/"
http.Handle(path, http.StripPrefix(
path, http.FileServer(http.Dir(dir))))
log.Printf("Serving: %s → %s", path, dir)
}
}
http.ListenAndServe(cfg.Server.Bind, nil)
}
func index(w http.ResponseWriter, r *http.Request) {
f, err := ioutil.ReadFile(currentConfig.Static.Index)
if err == nil {
w.Write(f)
}
}
func serveWS(ws *websocket.Conn) {
c := newClient(ws)
go c.writer()
c.run()
}
func Error(wrt, msg string) *errorMessage {
return &errorMessage{
Cmd: "!",
ReplyTo: wrt,
Message: msg,
}
}