echo

package module
v0.0.0-...-1aa35b3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

echo-server

Go codecov Docker Image Version (latest semver) Go Reference

An HTTP server that tells you exactly what it received. Point a proxy, load balancer, ingress, service mesh or HTTP client at it and see the request as it arrived: method, path, query, headers, cookies, body, client IP, TLS and which instance answered.

  • Any path, any method. JSON for clients, a readable page for browsers, the raw HTTP wire format on request.
  • Shape the response. Set the status, delay and response headers from the request itself.
  • WebSockets and SSE. Upgrade any path to a WebSocket echo, or stream server-sent events.
  • HTTP/2 everywhere. h2 over TLS and h2c (prior knowledge) over plaintext on the same port; mTLS client certs are shown.
  • Built for clusters. Liveness and readiness probes, graceful draining that closes streams, Prometheus metrics, JSON logs.
  • Small and static. One Go binary on a distroless, nonroot image with a built-in healthcheck, for amd64, arm64 and arm/v7.

Quick start

docker run --rm -p 8080:8080 syntaqx/echo-server
curl 'localhost:8080/hello?name=gopher' -H 'Content-Type: application/json' -d '{"hi":true}'
{
  "method": "POST",
  "url": "http://localhost:8080/hello?name=gopher",
  "path": "/hello",
  "query": { "name": ["gopher"] },
  "protocol": "HTTP/1.1",
  "host": "localhost:8080",
  "remote_addr": "172.17.0.1:40304",
  "client_ip": "172.17.0.1",
  "headers": {
    "Accept": ["*/*"],
    "Content-Length": ["11"],
    "Content-Type": ["application/json"],
    "User-Agent": ["curl/8.14.1"]
  },
  "content_length": 11,
  "body": {
    "content_type": "application/json",
    "size": 11,
    "encoding": "utf-8",
    "data": "{\"hi\":true}",
    "json": { "hi": true }
  },
  "server": { "hostname": "echo-7d9f4c", "version": "v0.1.0" },
  "request_id": "cda1afb896db4a7d",
  "time": "2026-11-10T08:56:05.391620915Z"
}

Open http://localhost:8080 in a browser to see the same request as a page, with copy-as-curl and a live WebSocket tester.

Prefer a binary? Download one for Linux, macOS, Windows or FreeBSD from Releases, or go install github.com/syntaqx/echo-server/cmd/echo-server@latest.

Image tags: latest and versions like 0.1 and 0.1.0 follow releases; main and nightly track the default branch.

Shaping the response

These work on every echoed path and on /status and /delay, as a request header or a query parameter:

Header Query parameter Effect
X-Echo-Status echo_status Respond with this status code (200–599).
X-Echo-Delay echo_delay Wait before responding: 250ms, 2s, or bare milliseconds.
X-Echo-Header echo_header Add a response header, Name: value. Repeatable.*
X-Echo-Format echo_format json, html, text (HTTP wire format) or raw (body only).
# A slow, failing upstream
curl -i localhost:8080/api -H 'X-Echo-Status: 503' -H 'X-Echo-Delay: 2s'

# Cache behaviour behind a CDN
curl -i 'localhost:8080/asset.js?echo_header=Cache-Control:max-age=60'

# The request as raw HTTP
curl 'localhost:8080/anything?echo_format=text'

# The body back verbatim, keeping its Content-Type
curl 'localhost:8080/?echo_format=raw' -H 'Content-Type: text/csv' --data-binary @data.csv

* Location, Refresh, Set-Cookie and Clear-Site-Data can only be set with the X-Echo-Header request header, not the query parameter: a query parameter works from a plain link, which would make any echo-server an open redirect and a cookie-planting tool for its domain.

Without a format, browsers (Accept: text/html) get HTML, Accept: text/plain gets text and everything else gets JSON. Bodies are parsed for JSON, URL-encoded forms and multipart uploads (files are summarized, not dumped). Binary bodies are base64-encoded. Bodies over -max-body are truncated in the echo, but size is always the full size. Chunked requests show transfer_encoding and any trailers; paths are echoed exactly as sent, including //, . and .. segments.

Every response carries X-Echo-Server (the hostname, handy behind a load balancer) and X-Request-Id (yours if you sent one).

Routes

Route Description
/* Echo the request. A WebSocket upgrade echoes messages back.
/status/{code} Echo with the given status code.
/delay/{duration} Echo after a delay.
/sse Server-sent events. ?interval=500ms&count=10. Interval 10ms–1h.
/healthz, /livez Liveness probe.
/readyz Readiness probe. Returns 503 once shutdown begins.
/metrics Prometheus metrics: requests, latency, in-flight, WebSockets.
/env Environment variables. Off unless -enable-env is set.
websocat ws://localhost:8080/ws                  # any echoed path upgrades
curl -N 'localhost:8080/sse?interval=500ms&count=5'
curl --http2-prior-knowledge localhost:8080/     # h2c; plain --http2 stays on HTTP/1.1

Need to echo /healthz or /metrics themselves? Proxying a real app's paths through the echo server can collide with these routes. Move them under a prefix and every other path is echoed:

docker run --rm -p 8080:8080 syntaqx/echo-server -route-prefix /_echo
curl localhost:8080/healthz          # echoed
curl localhost:8080/_echo/healthz    # liveness probe

Configuration

Every flag has an environment variable; flags take precedence. Invalid values, including malformed environment variables that no flag overrides, are rejected at startup (exit code 2) rather than silently ignored.

Flag Environment Default Description
-addr ECHO_ADDR or PORT :8080 Listen address. PORT alone sets the port.
-route-prefix ECHO_ROUTE_PREFIX Serve built-in routes under a prefix such as /_echo.
-tls-cert ECHO_TLS_CERT Certificate file; enables HTTPS and requests client certs.
-tls-key ECHO_TLS_KEY Private key file.
-log-format ECHO_LOG_FORMAT text text or json.
-log-level ECHO_LOG_LEVEL info debug, info, warn or error.
-access-log ECHO_ACCESS_LOG true Log each request. Probes and metrics scrapes are skipped.
-max-body ECHO_MAX_BODY 1048576 Max body bytes echoed (also the WebSocket message limit).
-max-delay ECHO_MAX_DELAY 30s Longest delay a client may request.
-enable-env ECHO_ENABLE_ENV false Serve /env. Environments often hold secrets.
-shutdown-delay ECHO_SHUTDOWN_DELAY 0s How long /readyz reports draining before shutdown starts.
-shutdown-timeout ECHO_SHUTDOWN_TIMEOUT 15s How long to wait for in-flight requests.
-state-file ECHO_STATE_FILE temp dir Where the server records its health URL for healthcheck.
Healthcheck

echo-server healthcheck exits 0 if the local server is healthy. The image's HEALTHCHECK uses it, so no curl or shell is needed. It finds the running server through the state file, so it keeps working however the server was started, including with flags like -addr :9000 -route-prefix /_echo or TLS. Pass -url to probe something specific. For HTTPS it verifies the server's certificate against the configured -tls-cert rather than skipping verification. Every failure exits 1, since Docker reserves 2.

Shutdown

On SIGTERM or SIGINT, /readyz starts returning 503, the server waits -shutdown-delay, then stops accepting connections. WebSockets are closed with 1001 (going away), SSE streams get a final close event, and pending delays respond early, so draining doesn't wait on long-lived connections. A second signal exits immediately.

-shutdown-delay defaults to 0 so docker stop and Ctrl-C are instant. Behind a load balancer, set it to a few seconds so traffic moves away before connections close.

Kubernetes
containers:
  - name: echo
    image: syntaqx/echo-server
    env:
      - { name: ECHO_LOG_FORMAT, value: json }
      - { name: ECHO_SHUTDOWN_DELAY, value: 5s }
    ports: [{ containerPort: 8080 }]
    livenessProbe: { httpGet: { path: /livez, port: 8080 } }
    readinessProbe: { httpGet: { path: /readyz, port: 8080 } }

As a Go library

The handler can be mounted in any server, including test servers. Until v1.0.0 the Go API may change between minor versions; the CHANGELOG lists every breaking change.

import echo "github.com/syntaqx/echo-server"

srv := httptest.NewServer(echo.New(echo.Options{}))
defer srv.Close()
// point your client, proxy or middleware at srv.URL

If you run it in your own http.Server, call srv.RegisterOnShutdown(h.CloseStreams) so Shutdown doesn't wait on open WebSockets and SSE streams, and keep any WriteTimeout above Options.MaxDelay.

Security

An echo server reflects whatever it's sent, cookies included, so:

  • Give it its own domain. Don't host it on a subdomain that receives cookies from a parent domain you care about. Anyone who can get a browser to visit it can see those cookies in the response.
  • Cross-origin reads never include credentials. CORS allows any origin but never sets Access-Control-Allow-Credentials, so other sites can't use a visitor's cookies to read their echo.
  • Links can't redirect or set cookies. The query-parameter form of echo_header refuses Location, Refresh, Set-Cookie and Clear-Site-Data.
  • Echoed content can't run as this site. Responses other than the HTML view are sent with Content-Security-Policy: sandbox and nosniff, even if a client sets Content-Type: text/html. The HTML view has a strict nonce-based CSP and escapes everything it shows.
  • client_ip isn't trusted. It honors Forwarded, X-Forwarded-For and X-Real-IP because showing what proxies send is the point, and any client can set those.
  • /env stays off unless you enable it.

Report vulnerabilities as described in SECURITY.md.

License

MIT

Documentation

Overview

Package echo implements an HTTP server that reflects every request back to the caller: method, path, headers, body, TLS details and more. It is meant for debugging proxies, load balancers, ingress controllers, service meshes and HTTP clients.

The handler returned by New can be mounted in any server, or used in-process with net/http/httptest:

srv := httptest.NewServer(echo.New(echo.Options{}))
defer srv.Close()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidatePrefix

func ValidatePrefix(p string) error

ValidatePrefix reports whether p can be used as Options.RoutePrefix: a clean absolute path such as "/_echo", without wildcards, query or fragment characters, spaces or control characters. A trailing slash is ignored.

Types

type Body

type Body struct {
	ContentType string `json:"content_type,omitempty"`
	// Size is the full body size in bytes, even when Data is truncated.
	Size int64 `json:"size"`
	// Truncated reports that the body exceeded Options.MaxBodyBytes, so Data
	// holds only the first MaxBodyBytes bytes and the body wasn't parsed.
	Truncated bool `json:"truncated,omitempty"`
	// Encoding is "utf-8" when Data is the body verbatim, "base64" for
	// binary payloads, or "omitted" for multipart uploads with files, which
	// are summarized in Files instead.
	Encoding string              `json:"encoding"`
	Data     string              `json:"data"`
	JSON     json.RawMessage     `json:"json,omitempty"`
	Form     map[string][]string `json:"form,omitempty"`
	Files    []File              `json:"files,omitempty"`
}

Body describes the request payload.

type Cookie struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

Cookie is one request cookie.

type Echo

type Echo struct {
	Method string `json:"method"`
	URL    string `json:"url"`
	Path   string `json:"path"`
	// Query is parsed from the raw query string, splitting only on "&", so
	// values containing ";" are kept rather than dropped.
	Query      map[string][]string `json:"query,omitempty"`
	Proto      string              `json:"protocol"`
	Host       string              `json:"host"`
	RemoteAddr string              `json:"remote_addr"`
	ClientIP   string              `json:"client_ip"`
	Headers    map[string][]string `json:"headers"`
	// ContentLength is the declared body length, or -1 when unknown (for
	// example a chunked body).
	ContentLength int64 `json:"content_length"`
	// TransferEncoding lists the transfer codings, such as "chunked". Go
	// removes the Transfer-Encoding header, so it is reported here instead.
	TransferEncoding []string `json:"transfer_encoding,omitempty"`
	// Cookies are in the order the client sent them; names may repeat.
	Cookies []Cookie `json:"cookies,omitempty"`
	Body    *Body    `json:"body,omitempty"`
	// Trailers are trailing headers sent after a chunked body.
	Trailers  map[string][]string `json:"trailers,omitempty"`
	TLS       *TLSInfo            `json:"tls,omitempty"`
	Server    ServerInfo          `json:"server"`
	RequestID string              `json:"request_id"`
	Time      time.Time           `json:"time"`
}

Echo is the reflection of a single request, as returned to the client.

type File

type File struct {
	Field       string `json:"field"`
	Filename    string `json:"filename"`
	ContentType string `json:"content_type,omitempty"`
	Size        int64  `json:"size"`
}

File summarizes one uploaded multipart file.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler is the echo server. Create one with New.

func New

func New(opts Options) *Handler

New returns a ready echo handler. It panics if opts.RoutePrefix is invalid; use ValidatePrefix to check user input first.

func (*Handler) CloseStreams

func (h *Handler) CloseStreams()

CloseStreams ends long-lived responses: WebSocket connections are closed with 1001 (going away), SSE streams end, and pending delays finish early. http.Server.Shutdown does not interrupt active handlers, so call this when shutting down, e.g. with srv.RegisterOnShutdown(h.CloseStreams). It is safe to call more than once.

func (*Handler) HealthPath

func (h *Handler) HealthPath() string

HealthPath is the path of the liveness probe, including any route prefix.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*Handler) SetReady

func (h *Handler) SetReady(ready bool)

SetReady toggles the /readyz endpoint. Call SetReady(false) when draining so load balancers stop routing new traffic before shutdown.

type Options

type Options struct {
	// MaxBodyBytes caps how much of a request body is read and echoed back.
	// Bodies larger than this are truncated in the echo. Defaults to 1 MiB.
	MaxBodyBytes int64

	// MaxDelay caps the artificial delay a client may request. Defaults to
	// 30s. The handler doesn't change your server's write deadline, so keep
	// http.Server.WriteTimeout (if set) comfortably above MaxDelay.
	MaxDelay time.Duration

	// RoutePrefix moves the built-in routes (/healthz, /metrics, /status/...,
	// etc.) under a prefix such as "/_echo", so every other path, including
	// /healthz, is echoed. Empty means the routes live at the root.
	RoutePrefix string

	// EnableEnv exposes the server's environment variables at /env. Off by
	// default because environments often contain secrets.
	EnableEnv bool

	// Hostname is reported in responses so callers can tell which instance
	// answered. Defaults to os.Hostname().
	Hostname string

	// Version is reported in responses and metrics.
	Version string

	// Logger receives access logs. Nil disables access logging.
	Logger *slog.Logger
}

Options configures the echo handler. The zero value is usable.

type ServerInfo

type ServerInfo struct {
	Hostname string `json:"hostname"`
	Version  string `json:"version"`
}

ServerInfo identifies the instance that answered.

type TLSInfo

type TLSInfo struct {
	Version            string   `json:"version"`
	CipherSuite        string   `json:"cipher_suite"`
	ServerName         string   `json:"server_name,omitempty"`
	NegotiatedProtocol string   `json:"alpn,omitempty"`
	Resumed            bool     `json:"resumed"`
	PeerCertificates   []string `json:"peer_certificates,omitempty"`
}

TLSInfo describes the TLS connection, when there is one.

Directories

Path Synopsis
cmd
echo-server command
Command echo-server runs an HTTP server that echoes requests back.
Command echo-server runs an HTTP server that echoes requests back.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL