gopp/server/handler.go

76 lines
1.5 KiB
Go

package server
import (
"vultras.su/util/tpp"
"path/filepath"
"net/http"
"path"
"mime"
"log"
"os"
"io"
)
var _ = http.Handler(&Handler{})
// The type describes behaviour
// of handling stuff like in PHP.
type Handler struct {
// THe field represents
// where we store site's
// source files and request handlers.
SourcePath string
// Preprocessor must be set by user
// to be able to bring custom features in.
PP *tpp.Preprocessor
// Aditional extension. ".tpp" by default.
// For example "file.html.tpp" will be
// first preprocessed TPP and sent back as simple HTML.
Ext string
}
func (h *Handler) ServeHTTP(
w http.ResponseWriter,
r *http.Request,
) {
urlPath := r.URL.Path
// Cleaning URL path to prevent injections.
urlPath = path.Clean(urlPath)
urlExt := path.Ext(urlPath)
filePath := filepath.Join(
filepath.FromSlash(h.SourcePath),
filepath.FromSlash(urlPath),
)
filePathTpp := filePath + h.Ext
//log.Println("pth:", urlPath, filePathTpp)
file, err := os.Open(filePathTpp)
if err != nil {
http.NotFound(w, r)
return
}
//process := true
fileData, err := io.ReadAll(file)
if err != nil {
http.NotFound(w, r)
return
}
processedData, err := h.PP.Process(
r.Context(),
true,
filePathTpp,
fileData,
)
if err != nil {
http.NotFound(w, r)
log.Printf("Error: pp.Process(...): %s\n", err)
return
}
contentType := mime.TypeByExtension(urlExt)
w.Header().Set("Content-Type", contentType)
w.Write(processedData)
}