Skip to content

Go 语言解决中文乱码问题

Published: at 02:05 AMSuggest Changes

终端里面跑 ping 命令的时候,终端输出的字符通过 go 程序再打印出来就乱码了,要做转换处理

import (
	"bytes"
	"fmt"
	"github.com/commander-cli/cmd"
	"golang.org/x/text/encoding/simplifiedchinese"
	"log"
	"os/exec"
)

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertByte2String(byte []byte, charset Charset) string {
	var str string
	switch charset {
	case GB18030:
		var decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}
	return str
}

func main() {
	cmd := exec.Command("ping", "www.baidu.com")
	var outb, errb bytes.Buffer
	cmd.Stdout = &outb
	cmd.Stderr = &errb
	newerr := cmd.Run()
	if newerr != nil {
		log.Fatal(newerr)
	}
	cmdStdout := ConvertByte2String([]byte(outb.String()), "GB18030")
	cmdStderr := ConvertByte2String([]byte(errb.String()), "GB18030")
	fmt.Println("out:", cmdStdout, "err:", cmdStderr)
}

Previous Post
保持 Go 程序持续运行
Next Post
获取和设置环境变量