GOPackageHeaderServer/web/pagehandler.go

58 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-07-11 21:47:22 +01:00
package web
import (
_ "embed"
2022-07-11 21:47:22 +01:00
"golang.captainalm.com/GOPackageHeaderServer/outputMeta"
"html/template"
2022-07-11 21:47:22 +01:00
"net/http"
"strconv"
)
type PageHandler struct {
Name string
CSS string
2022-07-11 21:47:22 +01:00
OutputPage bool
MetaOutput *outputMeta.PackageMetaTagOutputter
}
//go:embed outputpage.html
var outputPage string
var pageTemplateFuncMap template.FuncMap = template.FuncMap{
"isNotEmpty": func(stringIn string) bool {
return stringIn != ""
},
}
2022-07-11 21:47:22 +01:00
func (pgh *PageHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if request.Method == http.MethodGet || request.Method == http.MethodHead {
tmpl, err := template.New("page-handler").Funcs(pageTemplateFuncMap).Parse(outputPage)
if err != nil {
writeResponseHeaderCanWriteBody(request.Method, writer, http.StatusInternalServerError, "Page Template Parsing Failure")
return
}
tm := handlerTemplateMarshal{
PageHandler: *pgh,
RequestPath: request.URL.Path,
2022-07-11 21:47:22 +01:00
}
theBuffer := &BufferedWriter{}
err = tmpl.Execute(theBuffer, tm)
if err != nil {
writeResponseHeaderCanWriteBody(request.Method, writer, http.StatusInternalServerError, "Page Template Execution Failure")
return
2022-07-11 21:47:22 +01:00
}
writer.Header().Set("Content-Length", strconv.Itoa(len(theBuffer.Data)))
2022-07-11 21:47:22 +01:00
writer.Header().Set("Content-Type", "text/html; charset=utf-8")
if writeResponseHeaderCanWriteBody(request.Method, writer, http.StatusOK, "") {
_, _ = writer.Write(theBuffer.Data)
2022-07-11 21:47:22 +01:00
}
} else {
writer.Header().Set("Allow", http.MethodOptions+", "+http.MethodGet+", "+http.MethodHead)
if request.Method == http.MethodOptions {
writeResponseHeaderCanWriteBody(request.Method, writer, http.StatusOK, "")
} else {
writeResponseHeaderCanWriteBody(request.Method, writer, http.StatusMethodNotAllowed, "")
}
}
}