package main
import (
"errors"
"fmt"
"html/template"
"log"
"net/http"
"os"
"strconv"
)
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
}
// set custom status message if present
description, ok := Statuses[request]
if ok {
status.Message = description
}
return status
}
func main() {
// 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)
})
var address = fmt.Sprintf("%s:%s", os.Getenv("BIND"), os.Getenv("PORT"))
log.Fatal(http.ListenAndServe(address, nil))
}