2020-11-30 15:29:44 +07:00
|
|
|
package handler
|
|
|
|
|
2020-12-01 14:16:56 +07:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
var fs = http.FileServer(http.Dir("static/"))
|
2020-11-30 15:29:44 +07:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
2020-12-01 14:16:56 +07:00
|
|
|
if r.URL.Path == "/style.css" {
|
|
|
|
TemplateStyle(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if Static(w, r) {
|
|
|
|
return
|
|
|
|
}
|
2020-11-30 15:29:44 +07:00
|
|
|
Post(w, r)
|
|
|
|
}
|
2020-12-01 14:16:56 +07:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|