Home  >  Article  >  Backend Development  >  What to do if golang embeds garbled code

What to do if golang embeds garbled code

藏色散人
藏色散人Original
2020-04-08 10:43:383020browse

What to do if golang embeds garbled code

#What should I do if golang embeds garbled characters? Golang Chinese garbled code problem

#In the process of learning golang to read files, I encountered the problem of Chinese displaying garbled code! golang does not have its own codec package, so you need to use third-party packages

Solution:

Introduce the third transcoding package: git clone https:// github.com/axgle/mahonia.git

Then go directly to the code:

package main
import (
   "bufio"
   "fmt"
   "io"
   "mahonia"  //编码转换
   "os"
)
func main() {
   var enc mahonia.Decoder
   enc = mahonia.NewDecoder("gbk")
   //读取文件的案例
   //读取文件的内容并显示在终端,使用os.Open, file.Close, bufio.NewReader(), reader.ReadString
   file, err := os.Open("e:/test.txt")
   if err != nil {
      fmt.Println("open file err=", err)
   }
   //当函数退出时,要及时关闭file
   defer file.Close() //防止内存泄露
   //创建一个 *Reader , 是带缓冲的, 默认缓冲区为4096个字节
   reader := bufio.NewReader(file)
   //循环读取文件的内容
   for {
      str, err := reader.ReadString('\n') //读到一个换行就结束
      if err == io.EOF { //io.EOF表示文件的末尾
         break
      }
      //输出内容
      fmt.Println("UTF-8 to GBK:", enc.ConvertString(str))
   }
   fmt.Println("文件读取结束")
}

For more golang knowledge, please pay attention to the golang tutorial column of the PHP Chinese website.

The above is the detailed content of What to do if golang embeds garbled code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn