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
|
package app
import (
"go-gentoo/pkg/app/handler/admin"
"go-gentoo/pkg/app/handler/auth"
"go-gentoo/pkg/app/handler/index"
"go-gentoo/pkg/app/handler/links"
"go-gentoo/pkg/config"
"go-gentoo/pkg/database"
"go-gentoo/pkg/logger"
"log"
"net/http"
)
// Serve is used to serve the web application
func Serve() {
database.Connect()
defer database.DBCon.Close()
auth.Init()
setRoute("/auth/login", auth.Login)
setRoute("/auth/logout", auth.Logout)
setRoute("/auth/callback", auth.Callback)
setProtectedRoute("/links/show", links.Show)
setProtectedRoute("/links/create", links.Create)
setProtectedRoute("/links/delete", links.Delete)
setProtectedRoute("/admin/", admin.Show)
setProtectedRoute("/", index.Handle)
fs := http.StripPrefix("/assets/", http.FileServer(http.Dir("/go/src/go-gentoo/assets")))
http.Handle("/assets/", fs)
logger.Info.Println("Serving on port: " + config.Port())
log.Fatal(http.ListenAndServe(":"+config.Port(), nil))
}
// define a route using the default middleware and the given handler
func setProtectedRoute(path string, handler http.HandlerFunc) {
http.HandleFunc(path, protectedMW(handler))
}
// mw is used as default middleware to set the default headers
func protectedMW(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if auth.IsValidUser(w, r) {
setDefaultHeaders(w)
handler(w, r)
} else {
http.Redirect(w, r, "/auth/login", 301)
}
}
}
// define a route using the default middleware and the given handler
func setRoute(path string, handler http.HandlerFunc) {
http.HandleFunc(path, mw(handler))
}
// mw is used as default middleware to set the default headers
func mw(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setDefaultHeaders(w)
handler(w, r)
}
}
// setDefaultHeaders sets the default headers that apply for all pages
func setDefaultHeaders(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-cache")
}
|