diff options
Diffstat (limited to 'pkg/app/serve.go')
-rw-r--r-- | pkg/app/serve.go | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/pkg/app/serve.go b/pkg/app/serve.go new file mode 100644 index 0000000..fc2cdc3 --- /dev/null +++ b/pkg/app/serve.go @@ -0,0 +1,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") +} |