在Go中,我正在尝试简单的数据库连接。我需要导入 gorilla/mux
但我不能。
我使用的是VS Code。在 cd
的项目目录,我创建了 main.go
并确实运行 go get -u github.com/gorilla/mux
这里是 main.go
package main
import (
"database/sql"
"fmt"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 3000
user = "postgres"
password = "postgres"
dbname = "test1"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
[注意,在执行了 go get -u github.com/gorilla/mux
终端显示
C:\Go\src\github.com\IamFrost\go-rest-api>go get -v -u github.com/gorilla/mux
go: golang.org/x/text upgrade => v0.3.2
go: golang.org/x/crypto upgrade => v0.0.0-20200429183012-4b2356b1ed79
go: golang.org/x/sys upgrade => v0.0.0-20200430082407-1f5687305801
go: golang.org/x/net upgrade => v0.0.0-20200425230154-ff2c4b7c35a0
go: downloading golang.org/x/sys v0.0.0-20200430082407-1f5687305801
golang.org/x/sys/cpu
golang.org/x/crypto/chacha20poly1305
crypto/tls
]
看,我在小地图中没有其他语法错误。在红色标记处,当我把鼠标放在悬停文字上时,我觉得很有趣。
1)imported but not used
但下一行
2)no package for import github.com/gorilla/mux
)
lol这不是违背了1)吗?
谁来解释一下为什么会出现这种情况
然而,
使用后 go build
在 终端
这里是终端。
C:\Go\src\github.com\IamFrost\go-rest-api>go build
go: inconsistent vendoring in C:\Go\src:
github.com/gorilla/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
github.com/lib/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
golang.org/x/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
golang.org/x/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
golang.org/x/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
golang.org/x/[email protected]: is marked as explicit in vendor/modules.txt, but not explicitly required in go.mod
golang.org/x/[email protected]: is marked as explicit in vendor/modules.txt, but not explicitly required in go.mod
golang.org/x/[email protected]: is marked as explicit in vendor/modules.txt, but not explicitly required in go.mod
run 'go mod vendor' to sync, or use -mod=mod or -mod=readonly to ignore the vendor directory
[注:我也做了 "去mod vendor",但没有变化]
所以谁能告诉我为什么我不能导入 gorilla/mux
或 pq
.
我还需要做什么?
(请解释一下什么意思?is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
)
我不知道为什么它能工作(我是初学者)。我在net中找到了一些东西,不知怎么就成功了。下面是怎么做的。
1)这是我的go目录 C:\Go\
. 但我在我的桌面文件夹中创建项目
2)然后我在C:\Go\src下重新创建了一个项目(这是确切的文件夹C:\Go\src\github.com [github_username]\ [project_name] )
3)然后我把所有的代码粘贴到了 main.go
4)最后从终端 go mod vendor
5)然后 go build
6)然后 go run main.go
7)终于成功了
[我想知道为什么它的工作。我真的很感谢你的评论: 为什么他们强迫我去下。C:\Go\src
. 我已经有了 GOPATH C:\Go\
, GOBIN C:\Go\bin
设置在环境变量中]