实现说明
用 unicode.In 与 RangeTable 检测混合脚本标识符以函数 auditSlug、main为骨架。
迭代发生在 for _, r := range s 内部——循环之外的语句只执行一遍。
使用要点
- 全程不需调用包管理器——每条语句均基于内建 API 上。
main按顺序串起auditSlug;运行文件就会把这个流程跑一遍。
常见问题
「用 unicode.In 与 RangeTable 检测混合脚本标识符」这个示例怎么运行?
把它当完整程序编译/解释运行即可——不需要先安装任何东西。
入口签名:func auditSlug(s string) string
核心语句
for _, s := range samples {
fmt.Printf("%-20q -> %s\n", s, auditSlug(s))
}
for _, r := range s {
if unicode.In(r, unicode.Latin) {
hasLatin = true
} else if unicode.In(r, unicode.Cyrillic) {
hasCyrillic = true
} else if !unicode.In(r, slugExtra) {
hasDisallowed = true
}
}
return "blocked:mixed-latin-cyrillic"
代码示例
package main
import (
"fmt"
"unicode"
)
// Custom Range16 table (entries must be sorted ascending by Lo)
var slugExtra = &unicode.RangeTable{
R16: []unicode.Range16{
{Lo: '-', Hi: '-', Stride: 1},
{Lo: '0', Hi: '9', Stride: 1},
{Lo: '_', Hi: '_', Stride: 1},
},
LatinOffset: 3,
}
func auditSlug(s string) string {
var hasLatin, hasCyrillic, hasDisallowed bool
for _, r := range s {
if unicode.In(r, unicode.Latin) {
hasLatin = true
} else if unicode.In(r, unicode.Cyrillic) {
hasCyrillic = true
} else if !unicode.In(r, slugExtra) {
hasDisallowed = true
}
}
if hasLatin && hasCyrillic {
return "blocked:mixed-latin-cyrillic"
}
if hasCyrillic || hasDisallowed {
return "blocked:outside-allowlist"
}
return "allowed"
}
func main() {
samples := []string{
"api-gateway_v2",
"café-menu",
"p\u0430ypal-billing", // U+0430 is Cyrillic 'а'
"\u0442\u0435\u0441\u0442",
"docs/internal",
}
for _, s := range samples {
fmt.Printf("%-20q -> %s\n", s, auditSlug(s))
}
}