Home  >  Article  >  Backend Development  >  How to solve golang garbled code

How to solve golang garbled code

藏色散人
藏色散人Original
2019-12-25 11:27:093205browse

How to solve golang garbled code

How to solve the garbled code in golang?

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

Recommend learning "golang tutorial"

Solution:

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

Next 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("文件读取结束")
}

The above is the detailed content of How to solve golang 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
Previous article:Is golang open source?Next article:Is golang open source?