Add HTML Template to improve visual output
This commit is contained in:
65
src/main.go
65
src/main.go
@@ -2,22 +2,69 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type EchoData struct {
|
||||
Method string
|
||||
URL string
|
||||
Headers map[string][]string
|
||||
Body string
|
||||
}
|
||||
|
||||
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) {
|
||||
fmt.Fprintf(w, "%s %s\n", r.Method, r.URL.String())
|
||||
|
||||
fmt.Fprintln(w, "Headers:")
|
||||
for name, values := range r.Header {
|
||||
for _, value := range values {
|
||||
fmt.Fprintf(w, "%s: %s\n", name, value)
|
||||
bodyBytes, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintln(w, "\nBody:")
|
||||
r.Body.Close()
|
||||
data := EchoData{
|
||||
Method: r.Method,
|
||||
URL: r.URL.String(),
|
||||
Headers: r.Header,
|
||||
Body: string(bodyBytes),
|
||||
}
|
||||
|
||||
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() {
|
||||
|
||||
Reference in New Issue
Block a user