-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (90 loc) · 2.7 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
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bytes"
"encoding/json"
"flag"
"github.com/bcooksey/frontline/api"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"html/template"
"io/ioutil"
"log"
"net/http"
)
var (
tmplMain = "main.html"
templatePaths []string
templates *template.Template
reloadTemplates = true
logger *ServerLogger
inProduction = flag.Bool("production", false, "are we running in production")
configPath = flag.String("config", "config.json", "Path to configuration file")
sessionStore *sessions.CookieStore
config = struct {
Dbuser string
Dbpass string
sessionSecretKey string
}{
"",
"",
"",
}
)
func main() {
if *inProduction {
reloadTemplates = false
}
useStdout := !*inProduction
logger = NewServerLogger(256, 256, useStdout)
logger.Noticef("Starting Frontline Server...\n")
r := mux.NewRouter()
if err := readConfig(*configPath); err != nil {
log.Fatalf("Failed reading config file %s. %s\n", *configPath, err.Error())
}
sessionStore = sessions.NewCookieStore([]byte(config.sessionSecretKey))
// Root Views
r.HandleFunc("/", handleIndex)
r.HandleFunc("/login", handleLogin)
r.HandleFunc("/app", handleApp)
http.HandleFunc("/static/compiled/js/", handleStaticJs)
http.HandleFunc("/static/img/", handleStaticImg)
api.RegisterRoutes(r)
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8082", nil))
}
func GetTemplates() *template.Template {
if reloadTemplates || (nil == templates) {
templates = template.Must(template.ParseGlob("tmpl/*"))
}
return templates
}
func ExecTemplate(w http.ResponseWriter, templateName string) bool {
data := struct{}{}
return ExecTemplateWithContext(w, templateName, data)
}
func ExecTemplateWithContext(w http.ResponseWriter, templateName string, data interface{}) bool {
var buf bytes.Buffer
if err := GetTemplates().ExecuteTemplate(&buf, templateName, data); err != nil {
logger.Errorf("Failed to execute template '%s', error: %s", templateName, err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
} else {
// at this point we ignore error
w.Write(buf.Bytes())
}
return true
}
func serveErrorMsg(w http.ResponseWriter, msg string) {
http.Error(w, msg, http.StatusBadRequest)
}
func readConfig(configFile string) error {
b, err := ioutil.ReadFile(configFile)
if err != nil {
return err
}
err = json.Unmarshal(b, &config)
if err != nil {
return err
}
return nil
}