64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
var fs = http.FileServer(http.Dir("static/"))
|
|
|
|
// Index is the handler that displays the index page.
|
|
func Index(w http.ResponseWriter, r *http.Request) {
|
|
CurrentTheme.ExecuteTemplate(w, "index.tmpl", nil)
|
|
}
|
|
|
|
// Handler is the mux-ing handler.
|
|
func Handler(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/" {
|
|
Index(w, r)
|
|
return
|
|
}
|
|
if r.URL.Path == "/style.css" {
|
|
TemplateStyle(w, r)
|
|
return
|
|
}
|
|
if Static(w, r) {
|
|
return
|
|
}
|
|
Post(w, r)
|
|
}
|
|
|
|
// TemplateStyle is a handler that servers the style of the current template.
|
|
func TemplateStyle(w http.ResponseWriter, r *http.Request) {
|
|
if themeCSS == nil {
|
|
// 404 if the theme CSS doesn't exist as it's optional.
|
|
CurrentTheme.ExecuteTemplate(w, "404.tmpl", nil)
|
|
return
|
|
}
|
|
w.Header().Add("Content-Type", "text/css")
|
|
_, _ = w.Write(themeCSS)
|
|
}
|
|
|
|
// Static is a handler that serves static content if available.
|
|
// If it has served something (the static file or an error), it returns true.
|
|
func Static(w http.ResponseWriter, r *http.Request) bool {
|
|
fileName := "static" + r.URL.Path
|
|
|
|
// Check if the file exists and is not a directory.
|
|
info, err := os.Stat(fileName)
|
|
if os.IsNotExist(err) || (info != nil && info.IsDir()) {
|
|
return false
|
|
}
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
CurrentTheme.ExecuteTemplate(w, "500.tmpl", fmt.Errorf("error reading static folder: %w", err))
|
|
return true
|
|
}
|
|
|
|
// The file probably exist now. Even if there's a mismatch, the malicious attacker can only get a
|
|
// 404 or a directory listing.
|
|
fs.ServeHTTP(w, r)
|
|
return true
|
|
}
|