How to solve golang garbled code

藏色散人
Release: 2019-12-25 11:27:09
Original
3187 people have browsed it

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!