问题描述:
在使用Go语言获取网页信息时,默认解析为UTF8格式,如果出现GB2312的编码格式,则出现乱码,因此,使用创建探测函数确定网页编码方式。函数如下:
func determinEncoding(r *bufio.Reader) encoding.Encoding {
bytes, err := r.Peek(1024)
if err != nil {
log.Printf("fetch error : %v", err)
return unicode.UTF8
}
e, _, _ := charset.DetermineEncoding(bytes, "")
return e
}
在这个过程中需要依赖text、net等包,由于golang.org包的下载问题,这里采用直接git clone的方式下载到$GOPATH的src目录下,代码如下:
PANG@LAPTOP-PCSTF4VE MINGW64 /d/Go_WorkSpaces/go/src
$ git clone https://github.com/golang/text.git ./golang.org/x/text
$ git clone https://github.com/golang/net.git ./golang.org/x/net
但是在编译执行的时候出现如下错误:
main.go:6:2: cannot find module providing package golang.org/x/net/html/charset: working directory is not part of a module
main.go:7:2: cannot find module providing package golang.org/x/text/encoding: working directory is not part of a module
main.go:8:2: cannot find module providing package golang.org/x/text/encoding/unicode: working directory is not part of a module
main.go:9:2: cannot find module providing package golang.org/x/text/transform: working directory is not part of a module
问题分析:
一般网上的资料都是建议在工程的根目录下执行go mod init projectName命令。在执行go mod化之后,所有的引用都不再是以GOPATH为相对路径的引用了,而是变成了以go.mod中初始化的项目名为起始的引用。
PANG@LAPTOP-PCSTF4VE MINGW64 /d/Go_WorkSpaces/crawl
$ go mod init crawl
go: creating new go.mod: module crawl