golang检测网页编码

本文介绍了如何使用Golang来检测和处理网页编码,通过代码示例展示了在GBK编码环境下解决乱码问题的方法。

很简单直接上代码

演示就不判断错误了

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>
*/
......

打扰告辞,下篇文章再见。文章如有误请告知~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值