Skip to content

Commit cc5d809

Browse files
Copilotgaby
andauthored
docs: clarify AutoFormat HTML escaping behavior
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/e13b1223-74cf-4f5a-83f9-4c2cc4e2e9eb Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
1 parent 0b0d555 commit cc5d809

4 files changed

Lines changed: 10 additions & 2 deletions

File tree

ctx_interface_gen.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

ctx_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2151,6 +2151,12 @@ func Test_Ctx_AutoFormat_XSS_Prevention(t *testing.T) {
21512151
require.NoError(t, err)
21522152
require.Equal(t, "<p>Price: 5 &lt; 10 &amp; 20 &gt; 15</p>", string(c.Response().Body()))
21532153

2154+
// Test that pre-rendered HTML is treated as plain text
2155+
c.Request().Header.Set(HeaderAccept, MIMETextHTML)
2156+
err = c.AutoFormat("<b>Hello, World!</b>")
2157+
require.NoError(t, err)
2158+
require.Equal(t, "<p>&lt;b&gt;Hello, World!&lt;/b&gt;</p>", string(c.Response().Body()))
2159+
21542160
// Test that normal text without special chars works fine
21552161
c.Request().Header.Set(HeaderAccept, MIMETextHTML)
21562162
err = c.AutoFormat("Hello, World!")

res.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package fiber
33
import (
44
"bufio"
55
"fmt"
6-
"html"
76
"html/template"
87
"io"
98
"io/fs"
@@ -430,6 +429,7 @@ func (r *DefaultRes) Format(handlers ...ResFmt) error {
430429
// AutoFormat performs content-negotiation on the Accept HTTP header.
431430
// It uses Accepts to select a proper format.
432431
// The supported content types are text/html, text/plain, application/json, application/xml, application/vnd.msgpack, and application/cbor.
432+
// When text/html is selected, the body is treated as plain text and HTML-escaped before being wrapped in a <p> element.
433433
// For more flexible content negotiation, use Format.
434434
// If the header is not specified or there is no proper format, text/plain is used.
435435
func (r *DefaultRes) AutoFormat(body any) error {
@@ -458,7 +458,7 @@ func (r *DefaultRes) AutoFormat(body any) error {
458458
case "xml":
459459
return r.XML(body)
460460
case "html":
461-
return r.SendString("<p>" + html.EscapeString(b) + "</p>")
461+
return r.SendString("<p>" + template.HTMLEscapeString(b) + "</p>")
462462
case "msgpack":
463463
return r.MsgPack(body)
464464
case "cbor":

res_interface_gen.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)