Add HTML Template to improve visual output

This commit is contained in:
Fred Boniface
2025-12-05 21:04:07 +00:00
parent c6efed07f5
commit 5a08f02e09

View File

@@ -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(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Echo Server</title>
<style>
body { font-family: monospace; }
.header { font-weight: bold; margin-top: 1em; }
pre {margin: 4px; }
</style>
</head>
<body>
<h2>{{.Method}} {{.URL}}</h2>
<h3>Headers:</h3>
{{- range $name, $values := .Headers}}
<div class="header">{{$name}}</div>
<pre>{{- range, $_, $v := $values}} {{$v}}
{{- end}}</pre>
{{- end}}
<h3>Body:</h3>
<pre>
{{.Body}}
</pre>
</body>
</html>
`))
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() {