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 (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"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) {
|
func echoHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprintf(w, "%s %s\n", r.Method, r.URL.String())
|
bodyBytes, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
fmt.Fprintln(w, "Headers:")
|
http.Error(w, "Failed to read body: "+err.Error(), http.StatusBadRequest)
|
||||||
for name, values := range r.Header {
|
return
|
||||||
for _, value := range values {
|
|
||||||
fmt.Fprintf(w, "%s: %s\n", name, value)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Fprintln(w, "\nBody:")
|
|
||||||
r.Body.Close()
|
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() {
|
func main() {
|
||||||
|
|||||||
Reference in New Issue
Block a user