-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
107 lines (91 loc) · 2.14 KB
/
handlers.go
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
102
103
104
105
106
107
package main
import (
"errors"
"log"
"net/http"
"text/template"
ascii "ascii-art-web/output"
)
type output struct {
HasOutput bool
Color string
InitialText string
Text string
}
func Home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
err := errors.New("404\nPage not found")
ErrorPage(w, err, 404)
return
}
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
err := errors.New("405" + "\n" + "Method not allowed")
ErrorPage(w, err, 405)
return
}
ts, err := template.ParseFiles("./templates/index.html")
if err != nil {
log.Println(err.Error())
err = errors.New("500" + "\n" + "Internal Server Error")
ErrorPage(w, err, 500)
return
}
err = ts.Execute(w, nil)
if err != nil {
log.Println(err.Error())
ErrorPage(w, err, 500)
return
}
}
func AsciiDraw(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/ascii" {
err := errors.New("404\nPage not found")
ErrorPage(w, err, 404)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
err := errors.New("405" + "\n" + "Method not allowed")
ErrorPage(w, err, 405)
return
}
text := r.FormValue("text")
font := r.FormValue("font")
color := r.FormValue("color")
textWithFont, err := ascii.Asciiart(text, font)
t, err1 := template.ParseFiles("./templates/index.html")
if err1 != nil {
err1 = errors.New("500" + "\n" + "Internal Server Error")
ErrorPage(w, err1, 500)
return
}
if err != nil {
log.Println(err.Error())
err = errors.New("400" + "\n" + "Bad request")
ErrorPage(w, err, 400)
return
}
if text == "" || font == "" {
t.Execute(w, err)
return
}
data := output{true, color, text, textWithFont}
err = t.Execute(w, data)
if err != nil {
log.Println(err.Error())
err = errors.New("500" + "\n" + "Internal Server Error")
ErrorPage(w, err, 500)
return
}
}
func ErrorPage(w http.ResponseWriter, err error, code int) {
w.WriteHeader(code)
t, err1 := template.ParseFiles("./templates/error.html")
if err1 != nil {
http.Error(w, "500"+"\n"+"Internal Server Error", http.StatusInternalServerError)
return
}
t.Execute(w, err)
return
}