golang中文字符编码转换
golang默认使用的字符是UTF8,不过很多网页使用的是gbk编码,这时候就需要通过编码进行转换。具体代码如下:
1package main
2import "golang.org/x/text/encoding/simplifiedchinese"
3type Charset string
4const (
5 UTF8 = Charset("UTF-8")
6 GB18030 = Charset("GB18030")
7)
8func ConvertByte2String(byte []byte, charset Charset) string {
9 var str string
10 switch charset {
11 case GB18030:
12 var decodeBytes,_=simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
13 str= string(decodeBytes)
14 case UTF8:
15 fallthrough
16 default:
17 str = string(byte)
18 }
19 return str
20}
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/golang-iconv/5997.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.