gophertype/pkg/controllers/static_files.go

55 lines
1.3 KiB
Go
Raw Normal View History

2019-11-15 03:03:56 +00:00
package controllers
import (
"net/http"
"strings"
"git.kirsle.net/apps/gophertype/pkg/console"
2019-11-27 00:54:02 +00:00
"git.kirsle.net/apps/gophertype/pkg/models"
2019-11-15 03:03:56 +00:00
"git.kirsle.net/apps/gophertype/pkg/responses"
)
// CatchAllHandler handles the "/" and wildcard routes that are not
// picked up by any other controllers. It serves static files and Go
// templates from the builtin web root or the user root.
func CatchAllHandler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
2019-11-27 00:54:02 +00:00
// Is it a blog fragment?
if _, err := models.Posts.LoadFragment(path); err == nil {
PostFragment(w, r)
return
}
// No dot-files allowed.
if strings.Contains(path, "/.") {
console.Error("Path '%s' contains a dotfile; forbidden", path)
responses.Forbidden(w, r, "You're not supposed to be here.")
return
}
2019-11-15 03:03:56 +00:00
// Resolve the target path.
filepath, err := responses.ResolveFile(path)
if err != nil {
responses.NotFound(w, r)
2019-11-15 03:03:56 +00:00
return
}
// Files under /_builtin can only be taken literally.
if strings.HasPrefix(filepath, "_builtin/") {
responses.SendFile(w, r, filepath)
return
}
// Is it a Go template?
if strings.HasSuffix(filepath, ".gohtml") {
responses.RenderTemplate(w, r, filepath, nil)
2019-11-15 03:03:56 +00:00
return
2019-11-27 00:54:02 +00:00
} else if strings.HasSuffix(filepath, ".md") {
responses.RenderMarkdown(w, r, filepath)
return
2019-11-15 03:03:56 +00:00
}
2020-02-16 04:34:32 +00:00
responses.SendFile(w, r, filepath)
2019-11-15 03:03:56 +00:00
}