man*_*an3 6 windows cross-platform utf-8 character-encoding go
我正在编写一个接受用户输入的 golang 命令行程序。此输入字符串必须转换为 UTF-8 并发送到另一台服务器进行处理。在 Linux 上,终端编码几乎总是 UTF-8,但在 Windows 中似乎并非如此。我尝试使用将 Windows 上的代码页设置为 65001
chcp 65001
Run Code Online (Sandbox Code Playgroud)
并确保终端字体设置为 Lucida 控制台。但是,读取的字节
fmt.Scanf()
Run Code Online (Sandbox Code Playgroud)
不是 UTF-8 格式。我希望能够检测字符编码并将字符串转换为 UTF-8。同样,我应该能够在打印到屏幕之前从 UTF-8 转换为本地编码。
Python 似乎有“locale”包,它可以获取默认编码、解码和编码字符串到任何指定的编码。golang 有没有类似的东西?
大多数 stackoverflow 讨论都指向使用 chcp 65001 将 Windows 终端上的编码更改为 UTF-8。这似乎对我不起作用。
func main() {
foo := ""
fmt.Printf("Enter: ")
if _, err := fmt.Scanln(&foo) ; err != nil {
fmt.Println("Error while scanning: ", err)
}
fmt.Printf("Scanned bytes: % x", foo)
fmt.Println()
}
Run Code Online (Sandbox Code Playgroud)
在 Linux 上:
// ASCII
$ go run test.go
Enter: hello
Scanned bytes: 68 65 6c 6c 6f
// Unicode
$ go run test.go
Enter: ©
Scanned bytes: c2 a9
// Unicode
$ go run test.go
Enter: ???????
Scanned bytes: ce 86 ce 8f ce 91 ce 93 ce 94 ce 98 ce 9e ce a3 ce a8 ce a9 ce aa ce ad ce b1 ce b2 ce ba
Run Code Online (Sandbox Code Playgroud)
在 Windows 上:
PS C:\> chcp
Active code page: 437
PS C:\> go run .\test.go
Enter: hello
Scanned bytes: 68 65 6c 6c 6f
PS C:\> go run .\test.go
Enter: ???????
Scanned bytes: 3f 3f 61
// Change to Unicode
PS C:\> chcp 65001
Active code page: 65001
PS C:\> go run .\test.go
Enter: ???????
Error while scanning: EOF
Scanned bytes:
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助/指针。
| 归档时间: |
|
| 查看次数: |
1474 次 |
| 最近记录: |