2 Commits
0.0.1 ... main

Author SHA1 Message Date
a06d35e3db Fix invalid template 2025-12-05 22:25:15 +00:00
Fred Boniface
5a08f02e09 Add HTML Template to improve visual output 2025-12-05 21:04:07 +00:00

View File

@@ -2,22 +2,69 @@ package main
import ( import (
"fmt" "fmt"
"html/template"
"io"
"log" "log"
"net/http" "net/http"
) )
func echoHandler(w http.ResponseWriter, r *http.Request) { type EchoData struct {
fmt.Fprintf(w, "%s %s\n", r.Method, r.URL.String()) Method string
URL string
Headers map[string][]string
Body string
}
fmt.Fprintln(w, "Headers:") var echoTemplate = template.Must(template.New("echo").Parse(`
for name, values := range r.Header { <!DOCTYPE html>
for _, value := range values { <html lang="en">
fmt.Fprintf(w, "%s: %s\n", name, value) <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:") w.Header().Set("Content-Type", "text/html; charset=utf-8")
r.Body.Close() if err := echoTemplate.Execute(w, data); err != nil {
http.Error(w, fmt.Sprintf("Template error: %v", err), http.StatusInternalServerError)
}
} }
func main() { func main() {