-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
68 lines (57 loc) · 1.65 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
package main
import (
"fmt"
"log"
"net/http"
"path"
"regexp"
"github.com/togostanza/ts/provider"
)
var cmdServer = &Command{
Run: runServer,
Name: "server",
Short: "run server",
UsageLine: "server [-port port] [-stanza-base-dir dir] [-development]",
Long: "Run ts server for development",
}
var REGEXP_STANZA_PATH = regexp.MustCompile(`^/stanza/([^/]+)/`)
var flagServerDevelopment bool
func init() {
cmdServer.Flag.IntVar(&flagPort, "port", 8080, "port to listen on")
cmdServer.Flag.BoolVar(&flagServerDevelopment, "development", true, "development mode")
addBuildFlags(cmdServer)
}
func runServer(cmd *Command, args []string) {
sp, err := provider.New(flagStanzaBaseDir)
if err != nil {
log.Fatal(err)
}
distPath := path.Join(flagStanzaBaseDir, "dist")
distStanzaPath := path.Join(distPath, "stanza")
if err := sp.Build(distStanzaPath, flagServerDevelopment); err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
assetsHandler := http.FileServer(http.Dir(distPath))
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if req.URL.Path == "/" {
http.Redirect(w, req, "/stanza/", http.StatusFound)
return
}
if m := REGEXP_STANZA_PATH.FindStringSubmatch(req.URL.Path); len(m) > 0 {
if m[1] != "assets" {
err := sp.RebuildIfRequired(distStanzaPath, flagServerDevelopment)
if err != nil {
log.Println("ERROR during rebuild:", err)
}
}
}
assetsHandler.ServeHTTP(w, req)
})
addr := fmt.Sprintf(":%d", flagPort)
log.Println("listening on", addr)
if err := http.ListenAndServe(addr, mux); err != nil {
log.Fatal(err)
}
}