Files
old-riskletpy/application/controllers/index.go
2024-11-17 20:40:50 +01:00

54 lines
1.0 KiB
Go

package controllers
import (
"fmt"
"html"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
)
func Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Error: 404 %s not found.", html.EscapeString(r.URL.Path))
return
}
lp := filepath.Join("application", "layouts", "main.html")
fp := filepath.Join("application", "views", "index.html")
// Return a 404 if the template doesn't exist
info, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
// Return a 404 if the request is for a directory
if info.IsDir() {
http.NotFound(w, r)
return
}
tmpl, err := template.ParseFiles(lp, fp)
if err != nil {
// Log the detailed error
log.Print(err.Error())
// Return a generic "Internal Server Error" message
http.Error(w, http.StatusText(500), 500)
return
}
err = tmpl.ExecuteTemplate(w, "main.html", nil)
if err != nil {
log.Print(err.Error())
http.Error(w, http.StatusText(500), 500)
}
}