借“github.com/julienschmidt/httprouter“实践go mod
背景
执行如下代码,sublime找不到 “github.com/julienschmidt/httprouter”
package main import ( "fmt" "net/http" "log" "github.com/julienschmidt/httprouter" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome! ") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s! ", ps.ByName("name")) } func main() { router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) }
解决办法
一、环境变量要对,这几个都要设 set GO111MODULE=on set GOBIN=E:go-workspacein set GOPATH=E:go-workspace set GOROOT=C:Program FilesGo
二、 用 go get -u github.com/julienschmidt/httprouter 在E:go-workspacepkgmod下拉取三方库 发现拉下来的是 github.com/julienschmidt/httprouter@v1.3.0 不是 github.com/julienschmidt/httprouter 查看E:go-workspacepkgmodgithub.comjulienschmidthttprouter@v1.3.0下的go mod 发现里面的内容又是 module github.com/julienschmidt/httprouter go 1.7 对不上啊
自己写的代码import一个带版本后缀的库,发现提示如下错误: imports github.com/julienschmidt/httprouter@v1.3.0: can only use path@version syntax with ‘go get’ and ‘go install’ in module-aware mode 自己写的代码import一个不带版本后缀的库,发现又提示库找不到,可怕
而且用go mod download github.com/julienschmidt/httprouter@v1.3.0拉,还只能拉有版本后缀的库!!!
解决办法: 将 httprouter@v1.3.0 目录改名叫 httprouter,同时重新 go mod init httprouter 和 go mod tidy 这样就对上了
最后在自己的项目目录下 /e/go-workspace/src/demo1 执行: go mod init demo1 go mod tidy
再次编译就OK了