-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
101 lines (87 loc) · 2.38 KB
/
main.go
File metadata and controls
101 lines (87 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"embed"
"html/template"
"log"
"net/http"
"strconv"
"strings"
)
//go:embed 404.html error.html 404.png style.css
var content embed.FS
var errorMessages = map[int]string{
400: "Nieprawidłowe żądanie",
401: "Brak autoryzacji",
403: "Dostęp zabroniony",
404: "Strona której szukasz została wchłonięta przez grzyba",
405: "Metoda niedozwolona",
408: "Przekroczono limit czasu żądania",
429: "Zbyt wiele żądań",
500: "Wewnętrzny błąd serwera",
502: "Błąd bramy",
503: "Usługa niedostępna",
504: "Przekroczono limit czasu bramy",
}
type ErrorData struct {
Code int
Message string
}
func main() {
errorTmpl, err := template.ParseFS(content, "error.html")
if err != nil {
log.Fatalf("Failed to parse error template: %v", err)
}
// Serve static assets
http.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) {
data, _ := content.ReadFile("style.css")
w.Header().Set("Content-Type", "text/css")
w.Write(data)
})
http.HandleFunc("/404.png", func(w http.ResponseWriter, r *http.Request) {
data, _ := content.ReadFile("404.png")
w.Header().Set("Content-Type", "image/png")
w.Write(data)
})
// Serve 404 page (special case with image)
http.HandleFunc("/404", func(w http.ResponseWriter, r *http.Request) {
data, _ := content.ReadFile("404.html")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
w.Write(data)
})
// Helper to serve 404 page
serve404 := func(w http.ResponseWriter) {
data, _ := content.ReadFile("404.html")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
w.Write(data)
}
// Serve generic error pages
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
// Default to 404
serve404(w)
return
}
code, err := strconv.Atoi(path)
if err != nil || code < 100 || code > 599 {
serve404(w)
return
}
message, ok := errorMessages[code]
if !ok {
message = "Wystąpił błąd"
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(code)
errorTmpl.Execute(w, ErrorData{
Code: code,
Message: message,
})
})
log.Println("Starting error pages server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}