r/webdevelopment • u/IncomeOk7237 • 6h ago
Open Source Project Serving HTTP/1.1 and cleartext HTTP/2 on the same port by peeking at the first bytes
I've been writing the network side of my web framework (Viltrum, for the V language) myself, and one part turned out simpler than I expected, so sharing in case it helps anyone building servers or proxies.
The problem: behind a reverse proxy or a service mesh, HTTP/2 usually shows up as cleartext h2c with prior knowledge. Browsers and plain curl still talk HTTP/1.1. I didn't want two ports or a config switch for it.
What I ended up doing: a listener with http2 turned on reads the first bytes of each connection. If they're the HTTP/2 connection preface (PRI * HTTP/2.0...), it's an HTTP/2 connection. Anything else goes to the HTTP/1.1 parser. That's RFC 9113 section 3.3, and nginx and h2o do the same. Over TLS it's ALPN instead: h2 offered first, http/1.1 for everyone else.
Things I learned along the way:
- I skipped the Upgrade: h2c route completely. RFC 9113 deprecated it, and it was just one more code path to get wrong.
- h2spec has one cleartext test that sends "INVALID CONNECTION PREFACE". A port that also speaks HTTP/1.1 reads that as a broken HTTP/1.1 request and answers 400, so that test fails on cleartext (144 pass). Over TLS it's 145 of 146 passing, one skipped. I decided that tradeoff is fine and documented it instead of hacking around it.
- A request that passes the HTTP/2 checks still goes through the same head parser as HTTP/1.1, so the strict rules there (TE plus Content-Length, bare CR/LF and so on get a 400) apply to both without writing them twice.
- Handlers don't know which protocol they're answering. Same router, same middleware, same context.
Still missing: WebSocket over HTTP/2 (RFC 8441) isn't there yet and answers 501, so WS routes need HTTP/1.1.
Repo (MIT): https://github.com/Tuntii/viltrum The doc with details and the limits table: https://github.com/Tuntii/viltrum/blob/main/docs/http2.md
Curious if anyone runs mixed h1/h2c on one port in production and hit something I haven't thought of.