很简单直接上代码
演示就不判断错误了
package main
import (
"fmt"
"io/ioutil"
"net/http"
"unicode/utf8"
)
func main() {
resp, _ := http.Get(`https://www.baidu.com/`)
data, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Println(utf8.Valid(data)) // ture代表即utf8,否则你懂的
}
继续gbk网站测试看看
演示就不判断错误了
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, _ := http.Get(`http://www.dedecms.com/`)
dataByte, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Println(string(dataByte))
}
/* 输出乱码哈
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>֯��CMS �ٷ���վ - ���ݹ���ϵͳ - �Ϻ�����Ƽ�����˾</title>
<META NAME="Author" CONTENT="֯���Ŷ�">
......
*/
无敌模式,解决乱码
package main
import (
"fmt"
"golang.org/x/text/encoding/simplifiedchinese"
"io/ioutil"
"net/http"
"unicode/utf8"
)
func main() {
resp, _ := http.Get(`http://www.dedecms.com/`)
dataByte, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
sourceCode := string(dataByte)
if !utf8.Valid(dataByte) {
data, _ := simplifiedchinese.GBK.NewDecoder().Bytes(dataByte)
sourceCode = string(data)
}
fmt.Println(sourceCode)
}
/*
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>织梦CMS 官方网站 - 内容管理系统 - 上海卓卓网络科技有限公司</title>
*/
......
打扰告辞,下篇文章再见。文章如有误请告知~
本文介绍了如何使用Golang来检测和处理网页编码,通过代码示例展示了在GBK编码环境下解决乱码问题的方法。
753

被折叠的 条评论
为什么被折叠?



