From 64c3658d76ab0e5769c6d9b0b09a3c4350d6b655 Mon Sep 17 00:00:00 2001 From: Patricio Whittingslow Date: Wed, 29 Jul 2026 21:44:26 -0300 Subject: [PATCH] add Exchange.WriteBodyString --- http/httphi/exchange.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/http/httphi/exchange.go b/http/httphi/exchange.go index 59d182a..124cf77 100644 --- a/http/httphi/exchange.go +++ b/http/httphi/exchange.go @@ -6,6 +6,7 @@ import ( "slices" "strconv" "sync/atomic" + "unsafe" "github.com/soypat/lneto" "github.com/soypat/lneto/http/httpraw" @@ -319,6 +320,14 @@ func (rw *ExchangeRW) Write(buf []byte) (int, error) { return rw.exch.WriteBody(buf) } +// WriteString wraps [Exchange.WriteBodyString]. Fails if handle no longer valid. +func (rw *ExchangeRW) WriteString(s string) (int, error) { + if err := rw.validate(); err != nil { + return 0, err + } + return rw.exch.WriteBodyString(s) +} + // Read reads request body bytes. See [Exchange.ReadBody]. // Fails with [net.ErrClosed] once the handle is no longer valid. func (rw *ExchangeRW) Read(buf []byte) (int, error) { @@ -346,6 +355,12 @@ func (exch *Exchange) ReadWriter(dst *ExchangeRW) { dst.exch = exch } +// WriteBodyString implements [io.StringWriter] by unsafe conversion. +// Most underlying [io.Writer] implementations are TCP transport and not modify/own the underlying buffer. +func (exch *Exchange) WriteBodyString(buf string) (int, error) { + return exch.WriteBody(unsafe.Slice(unsafe.StringData(buf), len(buf))) +} + // Write writes response body bytes, flushing the header first if the handler // has not written it yet. Once a write to the connection fails the response is // unrecoverable and every later write returns that same error, so a body never