From 5a08f02e098ed681a5fb4ff595b2b32b08f91eda Mon Sep 17 00:00:00 2001 From: Fred Boniface Date: Fri, 5 Dec 2025 21:04:07 +0000 Subject: [PATCH] Add HTML Template to improve visual output --- src/main.go | 65 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/src/main.go b/src/main.go index 93276f2..50f2cd7 100644 --- a/src/main.go +++ b/src/main.go @@ -2,22 +2,69 @@ package main import ( "fmt" + "html/template" + "io" "log" "net/http" ) -func echoHandler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "%s %s\n", r.Method, r.URL.String()) +type EchoData struct { + Method string + URL string + Headers map[string][]string + Body string +} - fmt.Fprintln(w, "Headers:") - for name, values := range r.Header { - for _, value := range values { - fmt.Fprintf(w, "%s: %s\n", name, value) - } +var echoTemplate = template.Must(template.New("echo").Parse(` + + + + +Echo Server + + + +

{{.Method}} {{.URL}}

+ +

Headers:

+ +{{- range $name, $values := .Headers}} +
{{$name}}
+
{{- range, $_, $v := $values}} {{$v}}
+{{- end}}
+ +{{- end}} + +

Body:

+
+{{.Body}}
+
+ + +`)) + +func echoHandler(w http.ResponseWriter, r *http.Request) { + bodyBytes, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "Failed to read body: "+err.Error(), http.StatusBadRequest) + return + } + r.Body.Close() + data := EchoData{ + Method: r.Method, + URL: r.URL.String(), + Headers: r.Header, + Body: string(bodyBytes), } - fmt.Fprintln(w, "\nBody:") - r.Body.Close() + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := echoTemplate.Execute(w, data); err != nil { + http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError) + } } func main() {