Errorpages/main.go

90 lines
2.2 KiB
Go
Raw Normal View History

2023-11-24 19:00:35 +00:00
package main
import (
2023-11-24 22:22:19 +00:00
"errors"
2023-11-24 19:00:35 +00:00
"fmt"
2023-11-24 22:22:19 +00:00
"html/template"
2023-11-24 19:00:35 +00:00
"log"
"net/http"
2023-11-24 22:22:19 +00:00
"strconv"
2023-11-24 19:00:35 +00:00
)
2023-11-24 22:22:19 +00:00
type StatusData struct {
Code string
Message string
Response int
}
var Statuses = map[string]string{
"401": "You are not authorized to access the resource",
"404": "The requested resource couldn't be found",
"403": "Access to the resource was denied for the server",
"405": "Method not supported by the server",
"407": "You are no authorized to access the resource",
"408": "Request timed out",
"410": "The requested content is permanently gone",
"414": "Requested URI is too long",
"415": "Unsupported media type",
"500": "The server encountered an internal error",
"501": "Method not supported by the server",
"502": "Requested endpoint encountered an error",
"503": "Service is currently unavailable",
"504": "Requested endpoint is unreachable",
"505": "Protocol version not supported",
"511": "Requested endpoint requires authentication for proxy",
}
func isStatusCode(code string) (int, error) {
num, err := strconv.Atoi(code)
if err != nil {
return 500, errors.New("not a number")
}
if num > 99 && num < 512 {
return num, nil
}
return 500, errors.New("Invalid range")
}
func genStatus(request string) StatusData {
// create and init page status
var status StatusData
status.Code = "500"
status.Message = fmt.Sprintf("Invalid error response code recieved: %.5s[..]", request)
status.Response = 500
// check if we have a valid status code
var code, err = isStatusCode(request)
if err == nil {
status.Code = request
status.Message = fmt.Sprintf("Interrupted unsupported error response: %s", request)
status.Response = code
}
2023-11-24 19:00:35 +00:00
2023-11-24 22:22:19 +00:00
// set custom status message if present
description, ok := Statuses[request]
if ok {
status.Message = description
}
return status
2023-11-24 19:00:35 +00:00
}
func main() {
2023-11-24 22:22:19 +00:00
// load template
tmpl, err := template.ParseFiles("index-inlined-minified.html")
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
status := genStatus(r.URL.Path[1:])
// set status code to propagate http error code
w.WriteHeader(status.Response)
tmpl.Execute(w, status)
})
2023-11-24 19:00:35 +00:00
log.Fatal(http.ListenAndServe("127.0.0.1:8000", nil))
}