78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"embed"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"html/template"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
//go:embed static
|
||
|
var staticFS embed.FS
|
||
|
|
||
|
//go:embed templates
|
||
|
var templatesFS embed.FS
|
||
|
|
||
|
// Error model
|
||
|
type Error struct {
|
||
|
Title string `json:"title"`
|
||
|
Message string `json:"message"`
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
port := "5900"
|
||
|
|
||
|
http.Handle("/static/", http.FileServer(http.FS(staticFS)))
|
||
|
http.HandleFunc("/", errorHandler)
|
||
|
|
||
|
log.Printf("Listening on :%s...", port)
|
||
|
err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func errorHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
errorCode := r.URL.Query().Get("error")
|
||
|
|
||
|
// Load error messages from JSON file
|
||
|
jsonData, err := templatesFS.ReadFile("templates/errors.json")
|
||
|
if err != nil {
|
||
|
generateInternalServerError(w, err)
|
||
|
return
|
||
|
}
|
||
|
errors := make(map[string]Error)
|
||
|
err = json.Unmarshal(jsonData, &errors)
|
||
|
if err != nil {
|
||
|
generateInternalServerError(w, err)
|
||
|
return
|
||
|
}
|
||
|
errorData := errors[errorCode]
|
||
|
if errorData.Title == "" {
|
||
|
errorData.Title = "Error"
|
||
|
errorData.Message = "An error occurred."
|
||
|
}
|
||
|
|
||
|
// Render error page
|
||
|
tmpl, err := templatesFS.ReadFile("templates/error.html")
|
||
|
if err != nil {
|
||
|
generateInternalServerError(w, err)
|
||
|
return
|
||
|
}
|
||
|
t, err := template.New("error").Parse(string(tmpl))
|
||
|
if err != nil {
|
||
|
generateInternalServerError(w, err)
|
||
|
return
|
||
|
}
|
||
|
t.Execute(w, errorData)
|
||
|
}
|
||
|
|
||
|
func generateInternalServerError(w http.ResponseWriter, err error) {
|
||
|
log.Println(err)
|
||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
w.Write([]byte(`{"error": "Internal Server Error"}`))
|
||
|
}
|