ToValidUTF8 Repairs Broken Sequences
Sanitize hostile input with strings.ToValidUTF8, which replaces invalid UTF-8 byte runs with a fixed substitute string and leaves valid text untouched.
Code
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
// 截断多字节字符中间会产出非法 UTF-8:0xff 从不属于任何序列
valid := "ok, 世界"
broken := string([]byte{'l', 'o', 0xff, 'g', 0xfe})
fmt.Println("valid input:", utf8.ValidString(valid), "broken:", utf8.ValidString(broken))
// ToValidUTF8:非法字节段整体替换为占位符;合法文本原样保留
repaired := strings.ToValidUTF8(broken, "?")
fmt.Printf("repaired: %q valid: %t\n", repaired, utf8.ValidString(repaired))
// 连续非法字节算一段,只占一个占位符
mixed := string([]byte{0xff, 0xfe, 'a', 0xff})
fmt.Printf("collapsed: %q\n", strings.ToValidUTF8(mixed, "�"))
// 常见防线:外来数据入库前先修复
line := string(append(append([]byte("user typed: "), 0xc3, 0x28), " then more"...))
fmt.Printf("stored: %q\n", strings.ToValidUTF8(line, "\uFFFD"))
fmt.Println("roundtrip valid:", utf8.ValidString(strings.ToValidUTF8(line, "\uFFFD")))
}How the snippet works
Under the hood: the function main.
Points of care
- Built-in APIs only, so there is no supply chain to vet.
Using it
The run emits 5 labeled sections — valid input:, repaired:, collapsed:, stored:, roundtrip valid: — one per step.
Key statements
line := string(append(append([]byte("user typed: "), 0xc3, 0x28), " then more"...))
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does ToValidUTF8 Repairs Broken Sequences print when run?
- No setup needed: run the file and look for labeled lines like `valid input:`, `repaired:`, `collapsed:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.