Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c3bae1c

Browse files
committed
simpler truncating
1 parent c3bf516 commit c3bae1c

File tree

1 file changed

+3
-19
lines changed

1 file changed

+3
-19
lines changed

coderd/coderd.go

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -212,25 +212,9 @@ func FmtWebsocketCloseMsg(format string, vars ...any) string {
212212
// Cap msg length at 123 bytes. nhooyr/websocket only allows close messages
213213
// of this length.
214214
if len(msg) > websocketCloseMaxLen {
215-
// truncateString safely truncates a string to a maximum size of byteLen. It
216-
// writes whole runes until a single rune would increase the string size above
217-
// byteLen.
218-
truncateString := func(str string, byteLen int) string {
219-
builder := strings.Builder{}
220-
builder.Grow(byteLen)
221-
222-
for _, char := range str {
223-
if builder.Len()+len(string(char)) > byteLen {
224-
break
225-
}
226-
227-
_, _ = builder.WriteRune(char)
228-
}
229-
230-
return builder.String()
231-
}
232-
233-
return truncateString(msg, websocketCloseMaxLen)
215+
// Trim the string to 123 bytes. If we accidentally cut in the middle of
216+
// a UTF-8 character, remove it from the string.
217+
return strings.ToValidUTF8(string(msg[123]), "")
234218
}
235219

236220
return msg

0 commit comments

Comments
 (0)