-
Notifications
You must be signed in to change notification settings - Fork 1
/
webserver.go
209 lines (177 loc) · 5.37 KB
/
webserver.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"fmt"
"html/template"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/justinas/alice"
)
var sessionSecret = "KPSNvna729nvaAU10nAL"
var sessionStore = sessions.NewCookieStore([]byte(sessionSecret))
// siteData is stuff that stays the same
type siteData struct {
Title string
Port int
SessionName string
ServerDir string
DevMode bool
}
var site *siteData
// pageData is stuff that changes per request (and the site data)
type pageData struct {
Site *siteData
Title string
SubTitle string
Stylesheets []string
HeaderScripts []string
Scripts []string
FlashMessage string
FlashClass string
LoggedIn bool
Menu []menuItem
BottomMenu []menuItem
session *pageSession
TemplateData interface{}
}
func StartServer(dev bool) {
site = &siteData{
Title: "mcman",
Port: 8080,
SessionName: "mcman",
ServerDir: "./",
DevMode: dev,
}
r := mux.NewRouter()
r.StrictSlash(true)
if site.DevMode {
fmt.Println("Operating in Development Mode")
}
// Expose the public directory for CSS / JS assets. We could just use
// http.Handle on "/" and not do the StripPrefix but then the tmpls/
// directory would also be accessible. The "Dir" function is generated by
// the esc tool from "go generate"
r.PathPrefix("/assets/").Handler(http.FileServer(FS(site.DevMode)))
// Public Subrouter
pub := r.PathPrefix("/").Subrouter()
pub.HandleFunc("/", handleMain)
// Admin Subrouter
admin := r.PathPrefix("/admin").Subrouter()
admin.HandleFunc("/", handleAdmin)
admin.HandleFunc("/dologin", handleAdminDoLogin)
admin.HandleFunc("/dologout", handleAdminDoLogout)
admin.HandleFunc("/{category}", handleAdmin)
admin.HandleFunc("/{category}/{id}", handleAdmin)
admin.HandleFunc("/{category}/{id}/{function}", handleAdmin)
api := r.PathPrefix("/api/v1").Subrouter()
api.HandleFunc("/users/online", getOnlineUsers).Methods("GET")
api.HandleFunc("/users/whitelist", getWhitelist).Methods("GET")
api.HandleFunc("/users/ops", getOps).Methods("GET")
chain := alice.New(loggingHandler).Then(r)
output <- "* Site running at localhost:8080\n"
http.ListenAndServe(":8080", chain)
}
func initPageData(w http.ResponseWriter, req *http.Request) *pageData {
if site.DevMode {
w.Header().Set("Cache-Control", "no-cache")
}
p := new(pageData)
// Get the session
var err error
var s *sessions.Session
if s, err = sessionStore.Get(req, site.SessionName); err != nil {
http.Error(w, err.Error(), 500)
return p
}
p.session = new(pageSession)
p.session.session = s
p.session.req = req
p.session.w = w
// First check if we're logged in
userLogin, _ := p.session.getStringValue("login")
// TODO: With a valid account
p.LoggedIn = (userLogin != "")
if p.LoggedIn {
fmt.Println(">> Logged in")
} else {
fmt.Println(">> NOT logged in")
}
p.Site = site
p.Stylesheets = make([]string, 0, 0)
p.Stylesheets = append(p.Stylesheets, "/assets/vendor/css/pure-min.css")
p.Stylesheets = append(p.Stylesheets, "/assets/vendor/css/grids-responsive-min.css")
p.Stylesheets = append(p.Stylesheets, "/assets/vendor/font-awesome/css/font-awesome.min.css")
p.Stylesheets = append(p.Stylesheets, "/assets/css/mcman.css")
p.HeaderScripts = make([]string, 0, 0)
p.HeaderScripts = append(p.HeaderScripts, "/assets/js/B.js")
p.Scripts = make([]string, 0, 0)
p.Scripts = append(p.Scripts, "/assets/js/mcman.js")
p.FlashMessage, p.FlashClass = p.session.getFlashMessage()
if p.FlashClass == "" {
p.FlashClass = "hidden"
}
// Build the menu
if p.LoggedIn {
p.Menu = append(p.Menu, menuItem{"Admin", "/admin", "fa-key"})
p.BottomMenu = append(p.BottomMenu, menuItem{"Users", "/admin/users", "fa-user"})
p.BottomMenu = append(p.BottomMenu, menuItem{"Logout", "/admin/dologout", "fa-sign-out"})
} else {
p.BottomMenu = append(p.BottomMenu, menuItem{"Admin", "/admin", "fa-sign-in"})
}
return p
}
type templateData struct {
Menu []menuItem
}
type menuItem struct {
Label string
Location string
Icon string
}
func (p *pageData) show(tmplName string, w http.ResponseWriter) error {
fmt.Println("Showing Template: " + tmplName)
for _, tmpl := range []string{
"htmlheader.html",
"header.html",
tmplName,
"footer.html",
"htmlfooter.html",
} {
if err := outputTemplate(tmpl, p, w); err != nil {
fmt.Printf("%s\n", err)
return err
}
}
return nil
}
// outputTemplate
// Spit out a template
func outputTemplate(tmplName string, tmplData interface{}, w http.ResponseWriter) error {
n := "/templates/" + tmplName
l := template.Must(template.New("layout").Parse(FSMustString(site.DevMode, n)))
t := template.Must(l.Parse(FSMustString(site.DevMode, n)))
return t.Execute(w, tmplData)
}
// redirect can be used only for GET redirects
func redirect(url string, w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, url, 303)
}
func handleMain(w http.ResponseWriter, req *http.Request) {
var err error
fmt.Println(">> handleMain")
page := initPageData(w, req)
type indexData struct {
OnlineUsers []MCUser
}
id := new(indexData)
if id.OnlineUsers, err = c.model.getOnlineMCUsers(); err != nil {
fmt.Printf("> Error loading users: " + err.Error())
}
page.TemplateData = id
page.show("online-users.html", w)
}
func loggingHandler(h http.Handler) http.Handler {
return handlers.LoggingHandler(os.Stdout, h)
}