ehttp

package module
v0.0.0-...-63e4bc9 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 32 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

ehttp

ehttp is a Go HTTP framework and client. Its API is familiar to users of Express. It runs on the standard library net/http, so it keeps the robustness of Go.

  • Routes, route parameters, groups and middlewares, as in Express.
  • Strict checks. A mistake in a route or a header panics at boot or logs a warning, so it does not reach production unnoticed.
  • No hidden state. Each server has its own logger and its own configuration.
  • A small client with timeouts, a response size limit and redacted logs.

Requirements

ehttp needs Go 1.26.0 or later.

Install

go get github.com/EqualSoftware/ehttp

Quickstart

package main

import (
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/EqualSoftware/ehttp"
	"github.com/EqualSoftware/ehttp/middleware"
)

func main() {
	server := ehttp.NewServer(ehttp.WithPortInt(3000))

	server.Use(
		middleware.Recover(),
		middleware.Timeout(5*time.Second),
	)

	server.GET("/hello/:name", func(res *ehttp.ResponseWriter, req *ehttp.Request) {
		res.JSON(map[string]string{"message": "Hello, " + req.Param("name")})
	})

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	if err := server.Listen(ctx); err != nil {
		panic(err)
	}
}

Listen serves until the context is done. Then it finishes the requests in flight and returns. A clean shutdown returns nil.

For a longer guide, read examples/server/main.go.

Routes and parameters

Register a route with GET, POST, PUT, PATCH, DELETE, CONNECT or TRACE. Each method takes a pattern, a handler and optional middlewares.

  • :name is a route parameter. Read it with req.Param("name").
  • :name|regex is a parameter that must match the regular expression. The regex is anchored and compiled at registration.
  • ... matches the rest of the path. Check the value before you use it as a file path, for example with os.Root or filepath.IsLocal.

A request that does not match returns 404. A path that matches with another method returns 405 with an Allow header. An OPTIONS request returns the Allow header.

Groups and middleware order

server.Use adds middlewares to every route that is registered after the call. Call Use before the first route. A call after a route panics at boot.

server.Route(prefix, middlewares...) makes a group. The middlewares of a group run on the routes of the group. They also run on the 404, 405 and OPTIONS answers under the prefix. A second group with the same prefix panics.

admin := server.Route("/admin", basicAuth)
admin.GET("/me", handler)

The middlewares run in the order of the list, outside first. Use this order:

  1. middleware.Recover(): a panic becomes a 500. Put it first.
  2. middleware.ErrorCache(...): sets Cache-Control for error responses. Put it outside Timeout, so it covers the 503 of Timeout.
  3. middleware.RequestId(): sets X-Request-Id.
  4. middleware.Secure(middleware.DefaultSecureConfig): security headers.
  5. ehttp.Cors(...): the CORS policy. Put it before any authentication, so a preflight request and a refused request get the CORS headers.
  6. middleware.Timeout(...): a deadline on the request context.

Other middlewares are in the middleware package: AcceptEncoding, BodyLimit, Cache, ErrorCacheStatus, WeakEtag, LastModified and Log. Their rules are in the package documentation.

ResponseWriter

The *ehttp.ResponseWriter has these methods.

Method Use
Status(code) Set the status code. The body comes later.
StatusCode() Read the status code that is set.
SendStatus(code) Send a status line and no body.
Send(bytes) Send a body of bytes.
String(s) Send a text body.
JSON(v) Send a JSON body.
Render(name, data) Render a template. Set the templates with WithTemplates.
SendFile(name) Send a file. It sets a strong ETag and answers Range and conditional requests.
Redirect(url) Send a redirect.
Location(url) Set the Location header.
Error(err) Send an error response.
Set(name, value) Replace the value of a header.
Append(name, values...) Add members to a list header, such as Allow.
Remove(name) Remove a header.
Vary(names...) Add names to Vary.
Cookie(cookie) Set a cookie. Use it for Set-Cookie.
ClearCookie(name) Expire a cookie.
Header() The header map of the response.
HeadersSent() Report if the header was sent.
Flush(), FlushError() Send the buffered body to the client.
End() End the response.
Hijack(), Unwrap() Reach the connection or the standard writer.

Set and Append check their input. A mistake, such as an invalid name or a call after the header was sent, panics in Development mode. In Production mode it is logged and the header does not change. Set-Cookie and Vary have their own methods (Cookie and Vary).

CORS

ehttp.DefaultCorsOptions() allows every origin, method and header, with no credentials. For a public API without credentials, use it as it is. For other services, narrow the options:

o := ehttp.DefaultCorsOptions()
o.Origin = []string{"https://app.example.com"}
o.Methods = []string{ehttp.MethodGet, ehttp.MethodPost}
o.CacheDuration = 5 * time.Minute

server.Use(ehttp.Cors(o))

Put Cors before any authentication middleware.

Client

ehttp.NewClient makes a client. It sends a request with Execute.

client := ehttp.NewClient(
	ehttp.WithBaseUrl("https://api.example.com"),
	ehttp.WithTimeout(5*time.Second),
)

response, err := client.Execute(
	ehttp.WithContext(ctx),
	ehttp.WithSource("GET", "/items"),
)

The default total timeout of a request is 30 seconds. It also covers the read of the body.

Redirects use the standard library policy. On a redirect to another host, the client drops Authorization, WWW-Authenticate, Cookie, Cookie2, Proxy-Authorization and Proxy-Authenticate. A redirect to a subdomain of the first host keeps them.

Limits

Read these limits before you use ehttp in production.

  • Timeout is cooperative. middleware.Timeout sets a deadline on the request context. The handler runs in the same goroutine. It must watch req.Context(). If the deadline passes and no header was sent, the response is 503. A handler that does not watch the context keeps running.

  • No ClientIP. ehttp has no method that returns the client address. Use req.Request.RemoteAddr for the peer address. Read it through a trusted proxy with the guide below.

  • No Forwarded header. ehttp reads only the X-Forwarded-* headers from a trusted proxy. It does not read the Forwarded header of RFC 7239.

  • No built-in CSRF protection. ehttp has no CSRF middleware. Protect state changing requests in your application.

  • No default ReadTimeout or WriteTimeout. The server sets ReadHeaderTimeout to 10 seconds by default. ReadTimeout and WriteTimeout are off by default. Set them with WithReadTimeout and WithWriteTimeout when you need them.

  • WeakEtag buffers the response. The ETag covers the whole body, so the middleware keeps the body of a 200 response in memory until the handler ends. It buffers at most 1 MiB. A larger body is sent without an ETag.

  • One field line for Append. Append puts all members in one field line. It does not add a second line for the same header. Use Cookie for Set-Cookie.

  • Use frame-ancestors to control framing. middleware.Secure sets X-Frame-Options: SAMEORIGIN by default. Current browsers ignore the ALLOW-FROM value. To let specific origins put your pages in a frame, set the frame-ancestors directive through ContentSecurityPolicy:

    middleware.Secure(middleware.SecureOptions{
    	ContentSecurityPolicy: "frame-ancestors 'self' https://app.example.com",
    })
    

Trusted proxies

ehttp trusts no proxy by default. A request from a peer that is not trusted keeps its own scheme and host. Set the trusted peers with ehttp.WithTrustedProxies:

server := ehttp.NewServer(
	ehttp.WithTrustedProxies("loopback", "10.0.0.0/8"),
)

A value is a CIDR (10.0.0.0/8), a single IP (10.0.0.1), or one of these names:

Name Ranges
loopback 127.0.0.0/8, ::1/128
linklocal 169.254.0.0/16, fe80::/10
uniquelocal 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7

An invalid value panics at boot. Give only the peers that you run or trust. Do not give 0.0.0.0/0 or ::/0.

To find the peer ranges of your platform:

  • Kubernetes: use the pod network CIDR of the cluster, or the address range of the ingress controller. Your cluster administrator knows these values. ehttp does not publish them.
  • AWS Application Load Balancer: the load balancer nodes send requests from their private addresses and add X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Port. Trust the CIDRs of the load balancer subnets. Do not trust the full VPC CIDR: each host in the VPC can send a false X-Forwarded-For. The file https://ip-ranges.amazonaws.com/ip-ranges.json does not list the addresses of your own load balancers.
  • AWS Network Load Balancer: it works at layer 4 and does not add X-Forwarded-* headers. Do not add its addresses to the trusted list.
  • Google Cloud: a regional external Application Load Balancer sends requests from the proxy-only subnet of the region. Trust that subnet. For other load balancer types, find the source ranges in the firewall rules of https://docs.cloud.google.com/load-balancing/docs/tcp and https://docs.cloud.google.com/load-balancing/docs/health-check-concepts.
  • Cloudflare: the ranges are listed at https://www.cloudflare.com/ips-v4/ and https://www.cloudflare.com/ips-v6/.

Ranges change. Check the source of each platform again when you deploy.

Examples

The server example is a short guide to the API. Run it from the repository root:

go run ./examples/server

The client example shows a request to an external site.

Load and stress tests are in a separate repository: https://github.com/EqualSoftware/ehttp_benchmark.

Development

Run the gate of the project:

make check

make check runs the tests, the allocation tests, the lint, the vulnerability check and the list of known bugs. make tdd shows the open bugs as failures. make bench runs the benchmarks in Docker.

Dependabot updates the GitHub Actions and the Go modules every week. It does not track the tool versions that the Makefile pins (golangci-lint, govulncheck and benchstat). Update these versions by hand.

The scheduled workflows run the nightly fuzz tests and the weekly vulnerability check. GitHub disables scheduled workflows in a public repository after 60 days without activity. Run the workflow by hand to keep it active.

Security

To report a vulnerability, read SECURITY.md. Do not open a public issue for a vulnerability.

License

ehttp is released under the MIT License. See LICENSE. Copyright (c) 2026 Equal Software.

Documentation

Index

Constants

View Source
const (
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
)

HTTP methods were copied from net/http.

View Source
const (
	HeaderAccept         = "Accept"
	HeaderAcceptRanges   = "Accept-Ranges"
	HeaderAcceptLanguage = "Accept-Language"
	HeaderAcceptEncoding = "Accept-Encoding"
	// HeaderAllow is the name of the "Allow" header field used to list the set of methods
	// advertised as supported by the target resource. Returning an Allow header is mandatory
	// for status 405 (method not found) and useful for the OPTIONS method in responses.
	// See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLanguage     = "Content-Language"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderIfMatch             = "If-Match"
	HeaderIfNoneMatch         = "If-None-Match"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderRetryAfter          = "Retry-After"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedHost      = "X-Forwarded-Host"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-Ip"
	HeaderXRequestID          = "X-Request-Id"
	HeaderXCorrelationID      = "X-Correlation-Id"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderCacheControl        = "Cache-Control"
	HeaderConnection          = "Connection"
	HeaderEtag                = "Etag"
	HeaderUserAgent           = "User-Agent"
	HeaderRange               = "Range"
	HeaderContentRange        = "Content-Range"
	HeaderPragma              = "Pragma"
	HeaderReferrer            = "Referrer"
	HeaderPriority            = "Priority"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderSecFetchSite                    = "Sec-Fetch-Site"
	HeaderSecFetchDest                    = "Sec-Fetch-Dest"
	HeaderSecFetchUser                    = "Sec-Fetch-User"
	HeaderSecFetchMode                    = "Sec-Fetch-Mode"
	HeaderSecChUa                         = "Sec-Ch-Ua"
	HeaderSecCHUaMobile                   = "Sec-Ch-Ua-Mobile"
	HeaderSecChUaPlatform                 = "Sec-Ch-Ua-Platform"
)
View Source
const (

	// MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259
	MIMEApplicationJSON = "application/json"
	// Deprecated: Please use MIMEApplicationJSON instead. JSON should be encoded using UTF-8 by default.
	// No "charset" parameter is defined for this registration.
	// Adding one really has no effect on compliant recipients.
	// See RFC 8259, section 8.1. https://datatracker.ietf.org/doc/html/rfc8259#section-8.1
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types that are commonly used

View Source
const (
	StatusContinue           = http.StatusContinue
	StatusSwitchingProtocols = http.StatusSwitchingProtocols
	StatusProcessing         = http.StatusProcessing
	StatusEarlyHints         = http.StatusEarlyHints

	StatusOK                          = http.StatusOK
	StatusCreated                     = http.StatusCreated
	StatusAccepted                    = http.StatusAccepted
	StatusNonAuthoritativeInformation = http.StatusNonAuthoritativeInfo
	StatusNoContent                   = http.StatusNoContent
	StatusResetContent                = http.StatusResetContent
	StatusPartialContent              = http.StatusPartialContent
	StatusMultiStatus                 = http.StatusMultiStatus
	StatusAlreadyReported             = http.StatusAlreadyReported
	StatusIMUsed                      = http.StatusIMUsed

	StatusMultipleChoices   = http.StatusMultipleChoices
	StatusMovedPermanently  = http.StatusMovedPermanently
	StatusFound             = http.StatusFound
	StatusSeeOther          = http.StatusSeeOther
	StatusNotModified       = http.StatusNotModified
	StatusUseProxy          = http.StatusUseProxy
	StatusSwitchProxy       = 306
	StatusTemporaryRedirect = http.StatusTemporaryRedirect
	StatusPermanentRedirect = http.StatusPermanentRedirect

	StatusBadRequest                   = http.StatusBadRequest
	StatusUnauthorized                 = http.StatusUnauthorized
	StatusPaymentRequired              = http.StatusPaymentRequired
	StatusForbidden                    = http.StatusForbidden
	StatusNotFound                     = http.StatusNotFound
	StatusMethodNotAllowed             = http.StatusMethodNotAllowed
	StatusNotAcceptable                = http.StatusNotAcceptable
	StatusProxyAuthRequired            = http.StatusProxyAuthRequired
	StatusRequestTimeout               = http.StatusRequestTimeout
	StatusConflict                     = http.StatusConflict
	StatusGone                         = http.StatusGone
	StatusLengthRequired               = http.StatusLengthRequired
	StatusPreconditionFailed           = http.StatusPreconditionFailed
	StatusRequestEntityTooLarge        = http.StatusRequestEntityTooLarge
	StatusRequestURITooLong            = http.StatusRequestURITooLong
	StatusUnsupportedMediaType         = http.StatusUnsupportedMediaType
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable
	StatusExpectationFailed            = http.StatusExpectationFailed
	StatusTeapot                       = http.StatusTeapot
	StatusMisdirectedRequest           = http.StatusMisdirectedRequest
	StatusUnprocessableEntity          = http.StatusUnprocessableEntity
	StatusLocked                       = http.StatusLocked
	StatusFailedDependency             = http.StatusFailedDependency
	StatusTooEarly                     = http.StatusTooEarly
	StatusUpgradeRequired              = http.StatusUpgradeRequired
	StatusPreconditionRequired         = http.StatusPreconditionRequired
	StatusTooManyRequests              = http.StatusTooManyRequests
	StatusRequestHeaderFieldsTooLarge  = http.StatusRequestHeaderFieldsTooLarge
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons

	StatusInternalServerError           = http.StatusInternalServerError
	StatusNotImplemented                = http.StatusNotImplemented
	StatusBadGateway                    = http.StatusBadGateway
	StatusServiceUnavailable            = http.StatusServiceUnavailable
	StatusGatewayTimeout                = http.StatusGatewayTimeout
	StatusHTTPVersionNotSupported       = http.StatusHTTPVersionNotSupported
	StatusVariantAlsoNegotiates         = http.StatusVariantAlsoNegotiates
	StatusInsufficientStorage           = http.StatusInsufficientStorage
	StatusLoopDetected                  = http.StatusLoopDetected
	StatusNotExtended                   = http.StatusNotExtended
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired
)

Variables

View Source
var ErrRequestBodyTooLarge = errors.New("request body too large")
View Source
var ErrResponseTooLarge = errors.New("response body too large")

ErrResponseTooLarge is returned by Response.JSON, String and Bytes when the body is larger than the limit of WithMaxResponseBytes.

Functions

func CacheControl

func CacheControl(d time.Duration, private bool) string

CacheControl returns the Cache-Control value of SetCacheHeaderPrivate. It has no side effect. A middleware passes it to Own. A duration of zero or less gives no-store: a negative max-age is not valid (RFC 9111 §1.2.2). It does not check the duration: a duration under 1 second gives max-age=0. Use SetCacheHeader in a handler to get the strict check.

func SetCacheHeader

func SetCacheHeader(r *ResponseWriter, d time.Duration)

SetCacheHeader sets Cache-Control with Set. It is for a handler. A middleware that must own the field uses CacheControl with Own.

func SetCacheHeaderPrivate

func SetCacheHeaderPrivate(r *ResponseWriter, d time.Duration, private bool)

SetCacheHeaderPrivate is SetCacheHeader with a private flag. If private is true and d is not 0, the response gets the `private` directive: a shared cache must not store it (RFC 9111 §3.5).

A negative d, and a d above 0 and under 1 second, are mistakes of the developer: max-age takes whole seconds (RFC 9111 §1.2.2). In Development it panics. In Production it logs an error and sends no-store. A d of 1.5s is cut to 1 second.

func WithAuthorization

func WithAuthorization(value string) clientOptionFunc

func WithBaseUrl

func WithBaseUrl(value string) clientOptionFunc

func WithClientRedactNames

func WithClientRedactNames(patterns ...string) clientOptionFunc

WithClientRedactNames adds name patterns to the deny list of the client. It never replaces the default list. The syntax is the one of WithRedactNames. An invalid pattern panics.

func WithContext

func WithContext(value context.Context) requestOptionFunc

func WithHeader

func WithHeader(key, value string) requestOptionFunc

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) serverOption

WithIdleTimeout sets http.Server.IdleTimeout.

func WithJsonPayload

func WithJsonPayload(value interface{}) requestOptionFunc

func WithLogger

func WithLogger(l *zap.Logger) serverOption

WithLogger sets the logger of the server instead of the preset of WithMode. A nil logger panics. The server never changes the global zap logger.

func WithMaxHeaderBytes

func WithMaxHeaderBytes(n int) serverOption

WithMaxHeaderBytes sets http.Server.MaxHeaderBytes.

func WithMaxResponseBytes

func WithMaxResponseBytes(n int64) clientOptionFunc

WithMaxResponseBytes sets the largest body that Response.JSON, String and Bytes read. A value of 0 means no limit, which is the default. A negative value panics. If Content-Length is known and above the limit, the helpers return ErrResponseTooLarge without a read of the body. Else they stop at one byte over the limit. Response.Body stays unlimited, for streaming. The limit counts decoded bytes when the Transport decompresses gzip. If the caller sets Accept-Encoding by hand, the Transport does not decompress and the limit counts the compressed bytes. The limit is opt-in, as in resty (SetResponseBodyLimit) and req (SetMaxResponseSize).

func WithMode

func WithMode(m Mode) serverOption

WithMode picks the logger preset of the server. WithLogger wins over it, in any order of the options. An error from zap panics at boot.

func WithPort

func WithPort(v string) serverOption

WithPort sets the TCP port. It is a decimal number from 0 to 65535, where 0 lets the OS pick a free port. Any other value panics.

func WithPortInt

func WithPortInt(v int64) serverOption

WithPortInt is WithPort with a number.

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) serverOption

WithReadHeaderTimeout sets http.Server.ReadHeaderTimeout. The default is 10 s.

func WithReadTimeout

func WithReadTimeout(d time.Duration) serverOption

WithReadTimeout sets http.Server.ReadTimeout.

func WithRedactNames

func WithRedactNames(patterns ...string) serverOption

WithRedactNames adds name patterns to the deny list that hides values in the strict-mode logs and messages. It never replaces the default list (passwords, secrets, tokens, authentication data, sessions, cookies and similar names). A pattern ignores case and treats "-" as "_". "*x*" matches a name that contains x, "*x" a name that ends with x, "x*" a name that starts with x and "x" the name x. An invalid pattern panics.

func WithResponseWriter

func WithResponseWriter(res *ResponseWriter) (*ResponseWriter, *ResponseWriterInterceptor)

WithResponseWriter creates a new ResponseWriter with an interceptor as writer. The interceptor captures the response so a middleware can change it (for example etag) and then send it with SendResponse.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) serverOption

WithShutdownTimeout sets how long Listen waits for in-flight requests after its context is done. The default is 25 s, below the 30 s grace period of Kubernetes. Zero means no limit.

func WithSource

func WithSource(m, u string) requestOptionFunc

func WithStringPayload

func WithStringPayload(value string) requestOptionFunc

func WithTemplates

func WithTemplates(v string) serverOption

func WithTimeout

func WithTimeout(value time.Duration) clientOptionFunc

func WithTransport

func WithTransport(value *http.Transport) clientOptionFunc

func WithTrustedProxies

func WithTrustedProxies(cidrs ...string) serverOption

WithTrustedProxies sets the peers that can send X-Forwarded-* headers. A value is a CIDR, a single IP, or loopback, linklocal or uniquelocal. Without it, no peer is trusted. An invalid value panics.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) serverOption

WithWriteTimeout sets http.Server.WriteTimeout.

Types

type BreakerOptions

type BreakerOptions struct {
	Name string
	// Interval is the length of the rolling window of a closed breaker. Its
	// counts roll off bucket by bucket. Zero or less means 10s. The value is
	// rounded up to whole seconds (gobreaker adjusts it to a multiple of the 1 s
	// bucket). A value under 1s gives one bucket, so it is a fixed window.
	Interval        time.Duration
	Timeout         time.Duration
	PrometheusGauge *prometheus.GaugeVec
}

type CircuitBreaker

type CircuitBreaker[T any] = gobreaker.CircuitBreaker[T]

func NewCircuitBreaker

func NewCircuitBreaker[T any](opt BreakerOptions) *CircuitBreaker[T]

type Client

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

func NewClient

func NewClient(options ...clientOptionFunc) *Client

func (*Client) Execute

func (client *Client) Execute(options ...requestOptionFunc) (*Response, error)

Execute sends the request. A missing method or URL is an error, not a panic. The returned error of a failed request is a *url.Error that holds the URL path. The userinfo and the sensitive query values are masked (see WithClientRedactNames). Only the URL of the error is masked: the text of the wrapped error comes from net/http and can quote a value from the server, for example an unparsable redirect Location. Warn and Error logs of the client show only the scheme, the host and the method.

type CorsOptions

type CorsOptions struct {
	Origin        []string
	Methods       []string
	Headers       []string
	Credentials   bool
	CacheDuration time.Duration
}

CorsOptions sets the CORS policy of the Cors middleware. Origin must list at least one origin ("*" allows every origin). An empty Methods or Headers list means "*".

func DefaultCorsOptions

func DefaultCorsOptions() CorsOptions

DefaultCorsOptions returns a new policy that allows every origin, method and header, with no credentials. Change the copy before you pass it to Cors.

type Handler

type Handler interface {
	ServeHTTP(*ResponseWriter, *Request)
}

type HandlerFunc

type HandlerFunc func(res *ResponseWriter, req *Request)

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(res *ResponseWriter, req *Request)

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc func(next Handler) HandlerFunc

func Cors

func Cors(options CorsOptions) MiddlewareHandlerFunc

Cors returns the CORS middleware (Fetch §3.2). CORS is off unless the developer adds it with Use, on the server or on a group.

A preflight is an OPTIONS request with Origin and Access-Control-Request-Method (Fetch §3.2.2). The middleware answers it with 200, or 403 if the options do not allow it, and the chain ends there: the next middleware and the handler do not run, as a preflight is a standalone request (the same as go-chi/cors, Echo, gin-contrib/cors, Express cors and @fastify/cors). Place Cors before any middleware that can refuse a request without credentials, such as authentication, or the browser gets a refusal with no CORS headers. Any other request gets the CORS response headers, and the chain goes on.

The options are copied. An empty Origin list, Credentials with the "*" origin, an invalid entry and a negative CacheDuration panic at boot.

type Mode

type Mode int

Mode picks the preset of the server logger.

const (
	// Production is the default. The logger writes JSON at info level.
	Production Mode = iota
	// Development writes console output at debug level.
	Development
)

type Request

type Request struct {
	Request *http.Request
	// contains filtered or unexported fields
}

func (*Request) Accepts

func (req *Request) Accepts(value string) bool

Accepts reports if the Accept header allows the media type value. The answer depends on Accept, so it adds Accept to Vary (RFC 9110 §12.5.5).

A missing Accept header allows every type. The most specific media range that matches value sets its q value, and q=0 means not acceptable (RFC 9110 §12.4.2). Media type parameters in the header are ignored. An invalid header or an invalid value is never acceptable, so the caller answers with 406.

func (*Request) Body

func (req *Request) Body() ([]byte, error)

func (*Request) BodyJSON

func (req *Request) BodyJSON(v interface{}) error

func (*Request) BodyString

func (req *Request) BodyString() (string, error)

func (*Request) Context

func (req *Request) Context() context.Context

func (*Request) Cookie

func (req *Request) Cookie(name string) string

Cookie returns the value of the cookie name, or "" if it is absent.

func (*Request) Header

func (req *Request) Header(name string) string

func (*Request) Host

func (req *Request) Host() string

Host returns the Host header. A trusted proxy can set it with X-Forwarded-Host (see WithTrustedProxies).

func (*Request) Hostname

func (req *Request) Hostname() string

Hostname returns Host without the port, in lowercase (RFC 3986 §3.2.2).

func (*Request) Logger

func (req *Request) Logger() *zap.Logger

Logger returns the logger of the server with the fields request_id, method and route (the registered pattern). A field with an empty value is left out. The first call caches the logger, so a middleware that adds request data (for example RequestId) must run before the first call. It is safe to call from many goroutines.

func (*Request) Method

func (req *Request) Method() string

func (*Request) Origin

func (req *Request) Origin() string

func (*Request) Param

func (req *Request) Param(name string) string

Param returns a route param. The value is percent-decoded once, per segment (RFC 3986 §2.1). When a value has a ".." part (split on "/", literal or decoded), the router sends 403 and does not call the handler. A decoded NUL or backslash gives 400. A decoded "/" stays as data, and so does a "." part. Still confine a wildcard ("...") value before file use, for example with os.Root or filepath.IsLocal. Static segments compare the raw, still-escaped path, so "/us%65rs" does not match "/users".

func (*Request) Path

func (req *Request) Path() string

func (*Request) Protocol

func (req *Request) Protocol() string

Protocol returns "https" for a TLS connection and "http" otherwise. A trusted proxy can set it with X-Forwarded-Proto (see WithTrustedProxies).

func (*Request) Query

func (req *Request) Query(name string) string

func (*Request) RoutePath

func (req *Request) RoutePath() string

func (*Request) UserAgent

func (req *Request) UserAgent() string

func (*Request) WithContext

func (req *Request) WithContext(ctx context.Context) *Request

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

func (*Response) Bytes

func (res *Response) Bytes() ([]byte, error)

Read the response.Body as Bytes. It reads the full body into memory. The limit of WithMaxResponseBytes applies.

func (*Response) GetCacheControlMaxAge

func (res *Response) GetCacheControlMaxAge() time.Duration

Retrieve the response.Header Cache-Control max-age as time.Duration. All the Cache-Control lines are one list (RFC 9110 section 5.3). The directive name is not case-sensitive, and the value can be a quoted-string (RFC 9111 section 5.2). The value is delta-seconds: digits only (RFC 9111 section 1.2.2), and a value above 2^31 is 2^31. The first max-age directive wins (RFC 9111 section 4.2.1): if its value is invalid the result is zero, which means stale. A quote that does not end stops the scan of that line only: the next line is still read (an invalid directive is ignored).

func (*Response) JSON

func (res *Response) JSON(value interface{}) error

Read the response.Body as JSON. It reads the JSON value into memory. The limit of WithMaxResponseBytes applies.

func (*Response) String

func (res *Response) String() (string, error)

Read the response.Body as String. It reads the full body into memory. The limit of WithMaxResponseBytes applies.

type ResponseWriter

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

func (*ResponseWriter) Append

func (res *ResponseWriter) Append(name string, values ...string)

Append adds members to the list field name. All members go in one field line and a member that is already there (same bytes) is skipped. Each element of values is one member: nothing is split. It does nothing after the client is gone.

These are mistakes, as for Set: an empty member (Production skips it), a singleton field such as Content-Type (Production does a Set with the last value), an invalid name or value, Set-Cookie and Vary, a call after the header was sent. A field that a middleware set is not a mistake, as for Set.

Members are compared as whole strings. A value with a quoted comma, such as `rel="x, y"`, is not parsed.

func (*ResponseWriter) ClearCookie

func (res *ResponseWriter) ClearCookie(name string)

ClearCookie asks the client to delete the cookie name (Path "/").

func (*ResponseWriter) Cookie

func (res *ResponseWriter) Cookie(cookie *http.Cookie)

Cookie adds a Set-Cookie field line (RFC 6265 §3). It is the only field that can have many lines. A nil or invalid cookie and a call after the header was sent are mistakes, as for Set: Production does not send the cookie. It does nothing after the client is gone.

func (*ResponseWriter) End

func (res *ResponseWriter) End()

func (*ResponseWriter) Error

func (res *ResponseWriter) Error(e error)

func (*ResponseWriter) Flush

func (res *ResponseWriter) Flush()

Flush implements http.Flusher. See FlushError.

func (*ResponseWriter) FlushError

func (res *ResponseWriter) FlushError() error

FlushError sends the header and flushes the inner writer. It returns http.ErrNotSupported if the inner writer cannot flush (for example an interceptor). http.ResponseController uses it.

func (*ResponseWriter) Header

func (res *ResponseWriter) Header() http.Header

Header returns the raw header map. It is the escape hatch that http.ResponseWriter requires: nothing is validated, merged or checked here. Use Set, Append, Vary, Cookie and Remove for checked changes.

func (*ResponseWriter) HeadersSent

func (res *ResponseWriter) HeadersSent() bool

HeadersSent reports that the header was sent through the ResponseWriter, by a method or by a native handler (see WrapHandler), or, inside an interceptor, that the response was committed to the buffer. It does not track writes made through Unwrap.

func (*ResponseWriter) Hijack

func (res *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements http.Hijacker.

func (*ResponseWriter) JSON

func (res *ResponseWriter) JSON(v interface{})

func (*ResponseWriter) Location

func (res *ResponseWriter) Location(value string)

Location sets the Location field. See Set.

func (*ResponseWriter) Own

func (res *ResponseWriter) Own(name, value string)

Own sets the field name to value. In Development it also records that a middleware set the field. A handler can still change the field (the last writer wins), but Development then logs a warning: the handler overrides a middleware. Production records nothing and logs nothing.

Own is for middleware only. A middleware can call Own again to replace the value that another middleware set. Own has the checks of Set, and Vary and Set-Cookie have their own methods (OwnVary, Cookie). Pass a canonical name (for example "X-Xss-Protection") to avoid an allocation for each request.

func (*ResponseWriter) OwnVary

func (res *ResponseWriter) OwnVary(names ...string)

OwnVary is Vary, and it also keeps each name as a member that the handler cannot remove: Vary only grows (RFC 9110 §12.5.5). Both modes keep the members, and the header re-gets them before it goes out. Like Own, it is for middleware only.

func (*ResponseWriter) ReadFrom

func (res *ResponseWriter) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom, so io.Copy keeps the fast path of the inner writer.

func (*ResponseWriter) Redirect

func (res *ResponseWriter) Redirect(value string)

func (*ResponseWriter) Remove

func (res *ResponseWriter) Remove(name string)

Remove deletes the field name. The mistakes are the same as for Set; Vary has no Remove. It does nothing after the client is gone.

func (*ResponseWriter) Render

func (res *ResponseWriter) Render(name string, data interface{})

func (*ResponseWriter) Send

func (res *ResponseWriter) Send(v []byte)

func (*ResponseWriter) SendFile

func (res *ResponseWriter) SendFile(name string)

SendFile serves the file at the path name. It serves the path that the caller gives, so absolute paths and symbolic links are served. A path with a ".." element gets 404. Do not pass request data without validation.

A status set before SendFile other than 200 is the status of the response: the file is the body, and Range and the conditional fields are not used. Otherwise SendFile sets a strong ETag from the modification time and the size, answers the conditional fields and Range (RFC 9110 sections 13 and 14), and an If-Match or If-None-Match with an invalid syntax gets 400. The ETag is only as strong as the file mtime: a tool that restores the mtime (for example rsync -t, touch -d, or image layers with a fixed mtime) with new content of the same size keeps the same tag (RFC 9110 section 8.8.1).

func (*ResponseWriter) SendStatus

func (res *ResponseWriter) SendStatus(code int)

SendStatus sends the status line and no body. A code outside 200-599 and a call after the header was sent are mistakes, as for Status.

func (*ResponseWriter) Set

func (res *ResponseWriter) Set(name, value string)

Set replaces all values of the field name with value. These are mistakes: an invalid name or value, Set-Cookie and Vary (use Cookie and Vary) and a call after the header was sent. Development panics. Production logs and does not change the field. A field that a middleware set (see Own) is not a mistake: the handler value wins, and Development logs a warning. It does nothing after the client is gone.

func (*ResponseWriter) Status

func (res *ResponseWriter) Status(code int)

Status sets the final status code of the response. A code outside 200-599 and a call after the header was sent are mistakes: Development panics, Production logs and uses 500, or ignores the call after the send.

func (*ResponseWriter) StatusCode

func (res *ResponseWriter) StatusCode() int

StatusCode returns the status of the response. It is 200 until a handler sets another one.

func (*ResponseWriter) String

func (res *ResponseWriter) String(v string)

func (*ResponseWriter) Unwrap

func (res *ResponseWriter) Unwrap() http.ResponseWriter

Unwrap returns the inner writer, for http.ResponseController. A write through it is not tracked by HeadersSent.

func (*ResponseWriter) Vary

func (res *ResponseWriter) Vary(names ...string)

Vary adds names to the Vary field (RFC 9110 §12.5.5). It is the only way to change Vary. Each argument can list names with commas. An empty name is skipped, a name that is already there (ASCII case-insensitive) is skipped and "*" replaces all. Vary stays one field line. An invalid value and a call after the header was sent are mistakes, as for Set. It does nothing after the client is gone. A handler can add members to a Vary that a middleware set, but it cannot remove the members of the middleware.

func (*ResponseWriter) Write

func (res *ResponseWriter) Write(b []byte) (int, error)

Write implements http.ResponseWriter. It sends the header first, with the current status code.

func (*ResponseWriter) WriteHeader

func (res *ResponseWriter) WriteHeader(code int)

WriteHeader implements http.ResponseWriter. Only the first call counts.

type ResponseWriterInterceptor

type ResponseWriterInterceptor struct {
	http.ResponseWriter
	Buffer *bytes.Buffer
	Code   int
	Size   int64
	// contains filtered or unexported fields
}

func (*ResponseWriterInterceptor) SendResponse

func (i *ResponseWriterInterceptor) SendResponse(res *ResponseWriter)

func (*ResponseWriterInterceptor) Unwrap

Unwrap returns the real writer under the interceptor.

func (*ResponseWriterInterceptor) Write

func (i *ResponseWriterInterceptor) Write(b []byte) (int, error)

func (*ResponseWriterInterceptor) WriteHeader

func (i *ResponseWriterInterceptor) WriteHeader(code int)

type Router

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

func (*Router) CONNECT

func (r *Router) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) DELETE

func (r *Router) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) GET

func (r *Router) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) Handle

func (r *Router) Handle(method, pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

Handle registers a route. A group passes its own middlewares to its parent, so the middlewares of the outer group run first.

func (*Router) PATCH

func (r *Router) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) POST

func (r *Router) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) PUT

func (r *Router) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) Route

func (r *Router) Route(prefix string, m ...MiddlewareHandlerFunc) *Router

Route makes a group. The middlewares of a group run on its routes and, for a path under its prefix, on the 404, 405 and OPTIONS answers of the router (see ServeHTTP). A second group with the same prefix, other than a nested group of the first, panics: the answers of that prefix cannot pick one chain. The parameter name does not change the prefix, a regex does.

If a root route and a group route match the same path, the 405 and OPTIONS answers run the root middlewares only, and Allow lists the methods of both routes. To hide the methods of a protected route from unauthenticated clients, put every route of that path in one group that has the authentication middleware. Per-route middleware does not run on the automatic 405 and OPTIONS answers, so Allow still lists a method that only per-route middleware protects.

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves a request. The router answers itself when no route serves it: 404, 405 and the answer to OPTIONS. These answers run the middlewares of the root, and before them the middlewares of one group (the outer group first), so a middleware such as logging or CORS sees them:

  • 404: the innermost group whose prefix matches the path.
  • 405 and OPTIONS: the group that owns every route that matches the path. If the routes belong to several groups or to the root, only the root middlewares run, as the router cannot pick one group. Allow then lists the methods of all these routes. Per-route middleware never runs on these answers (see Route).

The refusals of an unsafe path value (400, 403) run the root middlewares only, so a group middleware never sees a path that was refused.

OPTIONS without a CORS preflight gets 200 with Allow and no body (RFC 9110 §9.3.7), and 404 for an unknown path. A preflight is answered by the CORS middleware (see Cors).

func (*Router) TRACE

func (r *Router) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Router) Use

func (r *Router) Use(m ...MiddlewareHandlerFunc)

Use adds middlewares that wrap each route registered after the call. It panics after a route was registered through this router (for a group: through the group or one of its subgroups), as a middleware added later would not wrap that route. Call Use before the routes (the rule of go-chi: "all middlewares must be defined before routes on a mux").

type Server

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

func NewServer

func NewServer(options ...serverOption) *Server

func (*Server) CONNECT

func (s *Server) CONNECT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) DELETE

func (s *Server) DELETE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) GET

func (s *Server) GET(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) Listen

func (s *Server) Listen(c context.Context) error

Listen serves until c is done, then shuts down gracefully. It returns a bind or serve error. A clean shutdown returns nil.

func (*Server) PATCH

func (s *Server) PATCH(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) POST

func (s *Server) POST(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) PUT

func (s *Server) PUT(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) Route

func (s *Server) Route(prefix string, m ...MiddlewareHandlerFunc) *Router

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes Server an http.Handler that serves requests through its router.

func (*Server) TRACE

func (s *Server) TRACE(pattern string, h HandlerFunc, m ...MiddlewareHandlerFunc)

func (*Server) Use

func (s *Server) Use(m ...MiddlewareHandlerFunc)

Directories

Path Synopsis
examples
client command
server command
Command server is a short guide to ehttp.
Command server is a short guide to ehttp.
internal
ehttptest
Package ehttptest holds the conventions shared by every ehttp test: each assertion carries its basis (a spec section or a reason), and known bugs run as strict expected failures.
Package ehttptest holds the conventions shared by every ehttp test: each assertion carries its basis (a spec section or a reason), and known bugs run as strict expected failures.
etag
Package etag reads the entity-tag lists of the If-Match and If-None-Match fields (RFC 9110 section 13.1.1 and 13.1.2).
Package etag reads the entity-tag lists of the If-Match and If-None-Match fields (RFC 9110 section 13.1.1 and 13.1.2).
fixtures
Package fixtures holds the servers, handlers and requests that the test suites share.
Package fixtures holds the servers, handlers and requests that the test suites share.
hook
Package hook lets the middleware package reach two functions of the ehttp package that are not public API.
Package hook lets the middleware package reach two functions of the ehttp package that are not public API.
redact
Package redact masks sensitive values before they reach a log or a message.
Package redact masks sensitive values before they reach a log or a message.
test
testapp
Package testapp builds the server that the golden and perf suites test.
Package testapp builds the server that the golden and perf suites test.

Jump to

Keyboard shortcuts

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