Files
echoreq/src/main.go

64 lines
1.3 KiB
Go

package main
import (
"embed"
"fmt"
"html/template"
"io"
"log"
"net/http"
)
//go:embed templates/*.html
var templates embed.FS
var echoTemplate = template.Must(
template.ParseFS(templates, "templates/echo.html"),
)
type EchoData struct {
Method string
URL string
Path string
Query string
Host string
Proto string
RemoteAddr string
Headers map[string][]string
Body string
TLS bool
}
func echoHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body: "+err.Error(), http.StatusBadRequest)
return
}
data := EchoData{
Method: r.Method,
URL: r.URL.String(),
Path: r.URL.Path,
Query: r.URL.RawQuery,
Host: r.Host,
RemoteAddr: r.RemoteAddr,
Proto: r.Proto,
Headers: r.Header,
Body: string(bodyBytes),
TLS: r.TLS != nil,
}
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() {
http.HandleFunc("/", echoHandler)
port := "8080"
log.Printf("Starting echo server on port %s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}