86 Commits
Author SHA1 Message Date
Kévin DunglasandKağan Küçük 857d5731f3 caddyhttp: optimise header access and fix encoding negotiation (#8025)
* perf: bypass header key normalization for canonical literals

http.Header's Get, Set, Add and Del run textproto.CanonicalMIMEHeaderKey
on every call. When the key is a canonical literal the result is the key
itself, so the scan is pure overhead. Access the map directly instead.

Only hot, allocation-free paths are converted, and only where the key is
a canonical literal. Call sites taking a key from config, a template or
the request itself still go through the normalizing methods, since they
need it for correctness.

allHeaderValues and lastHeaderValue dropped their http.CanonicalHeaderKey
call for the same reason: all callers pass canonical literals.

benchstat, Apple M5 Pro, go1.27.1:

    PrepareRequest-15      659.4n ± 2%  ->  457.7n ± 2%  -30.58% (p=0.000 n=12)
    AcceptedEncodings-15   330.8n ± 5%  ->  309.4n ± 7%   -6.44% (p=0.019 n=10)

    ResponseWriterWriteHeader/event-stream-15    1007.5n ± 3%  ->  732.5n ± 1%  -27.30%
    ResponseWriterWriteHeader/informational-15     60.0n ± 3%  ->   48.0n ± 2%  -20.01%
    ResponseWriterWriteHeader/not-modified-15     214.3n ± 6%  ->  175.3n ± 4%  -18.20%
    ResponseWriterWriteHeader/connect-15           60.2n ± 3%  ->   51.9n ± 4%  -13.85%
    ResponseWriterWriteHeader/html-15             206.5n ± 4%  ->  197.9n ± 2%   -4.19%
    geomean                                                                    -14.38%

Allocations are unchanged.

* tests: verify http.Header map keys are canonical

Indexing http.Header directly skips the canonicalization Get/Set/Add/Del
perform, which also puts the key outside what CI checks. canonicalheader
only inspects method calls. staticcheck's SA1008 covers reads, but stops
descending as soon as an assignment writes to a header, so it misses the
write, the delete builtin and the read-modify-write append. A key that is
not canonical in those positions is a silent lookup miss, not a compile
error.

Walk the loaded packages and verify every string constant used as a key in
an http.Header map operation matches http.CanonicalHeaderKey. A helper that
takes the key from its caller would hide the literal again, so a parameter
named with a canonical prefix opts its arguments into the same check.

The WebSocket headers Caddy deliberately writes with RFC 6455 casing are
allowed explicitly; they are only ever written out, never looked up against
a parsed header map.

Covers 64 operations, runs in under a second, and promotes golang.org/x/tools
from an indirect to a direct dependency at the version already in the module
graph.

* headercheck: resolve aliases of http.Header

* headercheck: check http.Header composite literal keys

* headercheck: note overlap with canonicalheader

* headercheck: drop parameter-name check

Helpers now take the indexed values, so every key sits in an index expression the analyzer and the linter already check.

* headercheck: scope RFC 6455 exceptions to their call sites

A key-based allow-list also accepted reads such as h["Sec-WebSocket-Key"], which miss because parsed headers are canonical. Honor //nolint:canonicalheader on the line instead, which the linter will use too.

* encode: read every Accept-Encoding field line

AcceptedEncodings read only the first field line, so a client that split
the list across several lines had the rest ignored. RFC 9110 section 5.3
treats repeated list-field lines as one comma-joined list. Iterate over
the items of every line instead of joining them, and skip empty items,
which used to yield an empty encoding. file_server's precompressed
selection uses the same function and is fixed with it.

Fixes https://github.com/caddyserver/caddy/issues/8272

Co-authored-by: Kağan Küçük <kaankck@gmail.com>

* encode: read every Cache-Control and Content-Encoding field line

Only the first field line was read, but RFC 9110 section 5.3 makes
multiple lines of a list-based field equivalent to one comma-joined
value:

- Cache-Control: no-transform on a later line was ignored, so the
  request or response was compressed anyway.
- Content-Encoding: an empty first line followed by a real coding let
  the handler encode the body a second time.

* encode: parse Cache-Control no-transform per RFC 9111

The substring match missed No-Transform, though RFC 9111 section 5.2 compares directive names case-insensitively, and fired on text that is not the directive: longer tokens such as x-no-transform-ext, quoted arguments such as community="no-transform", and semicolon-separated values, which are not valid Cache-Control syntax. Split the field on commas outside quoted strings and match only a well-formed no-transform element.

* encode: keep accepted encoding preferences on the stack

AcceptedEncodings counted commas to size the preference slice, and the variable capacity put it on the heap. A constant capacity covers typical Accept-Encoding headers and lets the compiler keep the slice on the stack; append still moves it to the heap for longer ones. BenchmarkAcceptedEncodings: 151.8ns -> 120.5ns (-21%), 192 -> 64 B/op, 2 -> 1 allocs/op (n=8).

* encode: build the encoded ETag without fmt

fmt.Sprintf boxed both arguments and parsed the format on every encoded response with a strong ETag. Concatenation: 47ns -> 16.5ns, 56 -> 24 B, 3 -> 1 allocs.

* reverseproxy: access response Server and Via headers directly

finalizeResponse runs on every proxied response; skip the key normalization as prepareRequest already does on the request side.

* encode: access headers directly in Write, WriteHeader and Close

These run once per response; convert the remaining literal-key Get, Set and Add calls like the rest of the handler.

* encode: match Cache-Control no-transform with httpguts

httpguts.HeaderValuesContainsToken already compares list elements case-insensitively across field lines, so the hand-written list parser is unnecessary. A no-transform inside a comma-separated quoted argument now also disables encoding, which only errs toward not transforming.

* encode: inline the no-transform check

isEncodeAllowed only wrapped one httpguts call. Its unit test now drives the response directive through ServeHTTP instead.

---------

Co-authored-by: Kağan Küçük <kaankck@gmail.com>
2026-10-29 23:19:50 +10:00
Jay Hemnani 093fd4b7ec encode: Don't write an empty encoded stream for HEAD responses (#8150)
* encode: Don't write an empty encoded stream for HEAD responses

When nothing was written (e.g. a HEAD request), Close() still closed the
encoder, which wrote the empty stream trailer to the client. The server
then set Content-Length to that size (20 for gzip, 13 for zstd) instead
of omitting it as for the matching GET response.

* encode: Check resp.ContentLength in the HEAD test

* encode: Track body writes to decide whether to close the encoder
2026-10-09 18:14:56 +10:00
Hitanshu 04fe161028 encode: fix ETag list matching (#8128) 2026-10-03 23:38:05 +10:00
Kévin DunglasandZen Dodd 2f34b936f5 feat: implement the Incremental header field (RFC 10036) (#8020)
Co-authored-by: Zen Dodd <mail@steadytao.com>
2026-10-02 20:59:34 -04:00
df44d6c383 encode: flush headers immediately for server-sent events responses (#7905)
* encode: flush headers immediately for server-sent events responses

The encode middleware withholds the response header until the first body
write so it can sniff content-type and apply the minimum_length threshold.
For a text/event-stream response the upstream typically writes headers and
flushes to establish the event stream before any event body is available,
so the client never received the headers and the stream stalled; the same
buffering also delayed individual events.

When WriteHeader sees a text/event-stream content type, initialize encoding
and write the header through immediately. Forcing the header out also marks
the response as started, so subsequent event writes bypass the minimum_length
buffering and stream to the client as they arrive.

Fixes #6293

* encode: add WriteHeader benchmark covering SSE fast path

* encode: replace mime.ParseMediaType with bound-checked SSE check

WriteHeader runs an SSE Content-Type check on every call once headers
haven't been written yet. mime.ParseMediaType parses the full media
type, including parameters, even when nothing matches, which shows up
on the hot header-write path.

Replace it with a bound-checked manual prefix/boundary check (isSSE),
skipping parameter parsing for the common non-SSE case.

* encode: reject content types with junk after text/event-stream

isSSE accepted any suffix after a space, so a value like
"text/event-stream nonsense" was treated as an SSE response. After the
media type, skip optional whitespace and require either the end of the
value or a parameter separator. The check remains allocation-free, so
the hot-path motivation for the manual matcher is preserved.

---------

Co-authored-by: SillyZir <269283839+SillyZir@users.noreply.github.com>
Co-authored-by: Kévin Dunglas <kevin@les-tilleuls.coop>
2026-08-01 00:27:28 +10:00
Julien Voisinand@dunglas 323e3fe4b7 encode: reduce allocations in AcceptedEncodings (#7847)
AcceptedEncodings runs for every request when response compression is enabled,
so its allocations contribute directly to per-request garbage and GC pressure.
While the gains are modest, this cuts allocations by two-thirds and bytes
nearly in half on a hot path that executes on every compressed request. Fewer
allocations means less work for the garbage collector, which at high request
rates translates into lower GC frequency and steadier tail latency, not just
faster execution of this one function in isolation.

For each token in the Accept-Encoding header it called strings.Split(accepted,
";"), allocating a throwaway slice per encoding, and grew the prefs slice from
empty. This commit replaces the per-token Split with strings.Cut (zero
allocation) and presize prefs from the comma count.

As requested per the policy, this commit adds a benchmark to exercise the
change. With header "gzip, deflate, br;q=0.9, zstd;q=0.8":

AcceptedEncodings
- sec/op  1158.5n -> 771.8n  (-33.38%)
- B/op 408 -> 216  (-47.06%)
- allocs/op 9 -> 3  (-66.67%)

Co-authored-by: @dunglas
2026-08-01 00:23:57 +10:00
Kévin Dunglas 3be8dabc89 caddyhttp: use canonical header key casing to avoid re-canonicalization (#7911)
Header.Get/Set re-canonicalize and allocate whenever the passed key
isn't already in canonical MIME header form. Sec-WebSocket-Key,
WWW-Authenticate, and content-type all miss the fast path; switch to
their canonical forms (Sec-Websocket-Key, Www-Authenticate,
Content-Type).

Enable the canonicalheader linter to catch future regressions,
excluded in test files since those already use non-canonical casing
in several places without a perf-sensitive path behind them.
2026-07-30 20:40:35 +10:00
Sam Ottenhoff 997d3f6b0a encode: add standard benchmark and conformance harness (#7804)
This is a shared encode_test harness with HTML/JSON/JS/CSS payloads taken from caddyserver.com

Benchmarks:
- BenchmarkStandardEncodingPayloads: raw encoder NewEncoder/Write/Close path
- BenchmarkEncodeHandlerCorpus: full Encode.ServeHTTP middleware path
- Grid: 4 payloads × gzip levels 1/5/9 × zstd fastest/default/best
- Each subtest runs with 4 parallel workers; compare runs on MB/s and allocs/op

Conformance tests:
- Encoder contract: Reset, Flush, Close, and pool-style Reset-after-Close reuse
- Corpus HTTP encoding: Content-Encoding, Vary, ETag suffix, header stripping
- Response semantics: minimum_length, 304, HEAD, range, WebSocket bypass,
  If-None-Match rewrite, Cache-Control no-transform, content-type matcher rejection
2026-06-11 17:55:18 -06:00
Muhammad Syafri, S.Kom 03e08ee6a9 encode: prioritize zstd and br over gzip in content negotiation (#7772)
* fix(encode): prioritize zstd and br over gzip in content negotiation

* test(encode): update unit tests to reflect new default priority ties

* fix(encode): move default preferences to dynamic encode handler and restore generic negotiation helper

* test(encode): call real Provision function in served-response test

* test(encode): rename served-response test to TestServeHTTPDefaultEncodingPreference

* refactor(encode): use slices.SortStableFunc and httptest.NewRecorder as recommended

* refactor(encode): simplify sorting with cmp.Compare and check request error in test

* test(encode): fix variable redeclaration in TestServeHTTPDefaultEncodingPreference

Fix 'no new variables on left side of :=' error by changing 'err :=' to 'err ='
on line 347, since err was already declared on line 332.

This fixes the build failure in the encode module tests.
2026-05-29 05:26:19 +10:00
Zen Dodd 88037f1666 chore: clean up wording and typo fixes (#7745)
* chore: clean up wording and typo fixes
* chore: ASCII -> alphanumeric in lexer for heredoc marker
2026-05-20 16:36:30 +10:00
Sam Ottenhoff 7a630f2910 encode: make zstd checksum configurable (#7586)
* http: make zstd checksum configurable

* disable_checksum
2026-03-28 13:07:21 -06:00
Matthew Holt 06a05e383c Revert "encode: Implement Flush for legacy compatibility"
This reverts commit bdcdaf77ba.
2026-02-27 14:14:19 -07:00
Matthew Holt bdcdaf77ba encode: Implement Flush for legacy compatibility
(By sponsor request)
2026-02-16 15:59:10 -07:00
ledigang 2cb426776c encode: modernize, replace HasSuffix+TrimSuffix with CutSuffix (#7357)
Signed-off-by: ledigang <shuangcui@msn.com>
2025-11-21 15:30:26 -07:00
wyrapeseed d115cd1042 chore: fix some comments (#7303) 2025-10-15 03:58:53 +00:00
Siomachkin 5473eb95d8 encode: fix response corruption when handle_errors is used (#7235)
* encode: fix response corruption when handle_errors is used

* Move disabled check before hdr assignment
2025-09-02 15:34:56 -06:00
aro-lew 806fef85be encode: add graphql-response header to list (#7214) 2025-08-27 14:58:14 -06:00
joemickyandMatt Holt 5125fbed41 use a more modern writing style to simplify code (#7182)
Signed-off-by: joemicky <joemickychang@outlook.com>
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
2025-08-20 11:41:21 -06:00
GreyXorandMohammed Al Sahaf 49dac61b07 bcrypt: add cost parameter to hash-password (#7149)
* feat: add bcrypt cost parameter to hash-password

* revert: typos

* refactor: take the cost out of interface

* fix: default bcrypt cost to 14

* fix: follow bcrypt library for min and max cost

* doc: mention defaultBcryptCost in cost parameter description

* chore: gci format

* fix: more specific bcrypt cost algorithm flag

* feat: bcrypt cost provisioning

* Revert "feat: bcrypt cost provisioning"

This reverts commit e09d4bd036.

* chore: gci format

* chore: gci format

* chore: gci format

* chore: golangcilint fmted

---------

Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-08-11 14:26:18 +03:00
minxinyi ab3b2d64ba refactor: use slices.Equal to simplify code (#7141)
Signed-off-by: minxinyi <minxinyi6@outlook.com>
2025-07-23 14:07:46 +00:00
WeidiDeng 5ba1e06fd6 encode: try to use sendfile when compression is not used (#6749)
* try to use sendfile when encode is enabled

* change variable name

* add comments

* remove connect check since it's done in Write method
2024-12-20 21:37:16 +00:00
WeidiDeng bcaa8aaf11 encode: write status immediate for success response for CONNECT requests (#6738)
* encode: write status immediate for success response for CONNECT requests

* fix compile

* fix test

* fix lint

* treat first write and flush for encode response writer to CONNECT request as success if status is not set explicitly
2024-12-11 11:15:01 -07:00
Kévin Dunglas d0e209e1da encode: good defaults (#6737)
* feat: good default for encode

* fix tests and add a new one
2024-12-10 16:48:30 -07:00
Francis Lavoie 2faeac0a10 chore: Use slices package where possible (#6585)
* chore: Use slices package where possible

* More, mostly using ContainsFunc

* Even more slice operations
2024-09-25 14:30:56 -06:00
WeidiDeng 976469ca0d encode: flush already compressed data from the encoder (#6471) 2024-07-27 17:46:56 -06:00
Kévin Dunglas 15d986e1c9 encode: Don't compress already-compressed fonts (#6432)
* fix: don't compress already compressed fonts

* fix: remove WOFF
2024-07-04 14:57:13 -06:00
Matthew Holt d00824f4a6 fileserver: Improve Vary handling (#5849) 2024-04-19 13:43:13 -06:00
Matthew Holt 9ab09433de encode: Slight fix for the previous commit 2024-04-17 19:59:10 -06:00
Matthew Holt 3067074d9c encode: Improve Etag handling (fix #5849)
We also improve Last-Modified handling in the file server.
Both changes should be more compliant with RFC 9110.
2024-04-17 19:12:03 -06:00
03e0a010d1 encode: Configurable compression level for zstd (#6140)
* Add zstd compression level support

* Refactored zstd levels to string arguments

fastest, default, better, best

* Add comment with list of all available levels

* Corrected data types for config

---------

Co-authored-by: Evgeny Blinov <e.a.blinov@gmail.com>
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
2024-04-16 00:21:52 +00:00
WeidiDengandFrancis Lavoie 1bd598e90c chore: encode: use FlushError instead of Flush (#6168)
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
2024-03-10 23:04:35 -04:00
WeidiDeng e698ec5139 encode: write status immediately when status code is informational (#6164) 2024-03-10 10:49:49 -04:00
Kévin Dunglas 2348ac897a update comment 2024-02-09 09:35:55 +01:00
Kévin Dunglas d3f23a8eeb improved list 2024-02-09 09:35:55 +01:00
Kévin Dunglas 60abd72c7a fix: add back text/* 2024-02-09 09:35:55 +01:00
Kévin Dunglas b8f729b88f fix: add more media types to the compressed by default list 2024-02-09 09:35:55 +01:00
Yolan RomaillerandFrancis Lavoie 2fe69a828f chore: enabling a few more linters (#5961)
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
2024-01-25 15:24:58 +00:00
Francis Lavoie 750d0b8331 caddyfile: Normalize & flatten all unmarshalers (#6037) 2024-01-23 19:36:59 -05:00
a c839a98ff5 filesystem: Globally declared filesystems, fs directive (#5833) 2024-01-13 20:12:43 +00:00
Christoph e0aaefab80 encode: Add application/wasm* to the default content types (#5869) 2023-10-10 21:18:37 +00:00
Jacob Gadikian d6f86cccf5 ci: use gci linter (#5708)
* use gofmput to format code

* use gci to format imports

* reconfigure gci

* linter autofixes

* rearrange imports a little

* export GOOS=windows golangci-lint run ./... --fix
2023-08-14 09:41:15 -06:00
Francis Lavoie 1913930783 encode: Fix infinite recursion (#5672) 2023-08-02 18:21:11 -06:00
Francis Lavoie cd486c25d1 caddyhttp: Make use of http.ResponseController (#5654)
* caddyhttp: Make use of http.ResponseController

Also syncs the reverseproxy implementation with stdlib's which now uses ResponseController as well https://github.com/golang/go/commit/2449bbb5e614954ce9e99c8a481ea2ee73d72d61

* Enable full-duplex for HTTP/1.1

* Appease linter

* Add warning for builds with Go 1.20, so it's less surprising to users

* Improved godoc for EnableFullDuplex, copied text from stdlib

* Only wrap in encode if not already wrapped
2023-08-02 20:03:26 +00:00
Kévin Dunglas 1c9ea0113d caddyhttp: Impl ResponseWriter.Unwrap(), prep for Go 1.20's ResponseController (#5509)
* feat: add support for ResponseWriter.Unwrap()

* cherry-pick Francis' code
2023-04-26 19:44:01 -04:00
WeidiDeng b3f0cea2c3 encode: flush status code when hijacked. (#5419) 2023-03-06 09:13:48 -07:00
darkweak dac7cacd4d encode: Respect Cache-Control no-transform (#5257)
* encode: respect Cache-Control HTTP header no-transform

* encode: switch to strings.Contains
2022-12-20 13:26:53 -07:00
Francis Lavoie ee7c92ec9b reverseproxy: Mask the WS close message when we're the client (#5199)
* reverseproxy: Mask the WS close message when we're the client

* weakrand

* Bump golangci-lint version so path ignores work on Windows

* gofmt

* ugh, gofmt everything, I guess
2022-11-14 09:38:02 -07:00
WeidiDeng 44ad0cedaf encode: don't WriteHeader unless called (#5060) 2022-09-21 08:30:42 -06:00
WeidiDeng 48d723c07c encode: Fix Accept-Ranges header; HEAD requests (#5039)
* fix encode handler header manipulation
also avoid implementing ReadFrom because it breaks when io.Copied to directly

* strconv.Itoa should be tried as a last resort
WriteHeader during Close
2022-09-15 16:05:08 -06:00
Simon Legner 66596f2d74 zstd: fix typo in comment (#4985) 2022-08-25 12:00:05 +03:00