猿问

在 golang 中使用/设置 sqlite3 的用户身份验证

我必须将我的数据库密码保护作为我学校的一项任务。例如,如果有人试图访问我的数据库,它会询问密码。
我正在尝试使用go-sqlite3包,并尝试阅读官方指南。
第一步是使用go build --tags <FEATURE>.
它给了我一个错误build .: cannot find module for path .
,我不知道为什么以及我们首先要构建什么。我也尝试搜索实际示例,但没有找到任何示例。

您能否向我解释如何使用 golangs go-sqlite3 包为我的数据库设置用户身份验证?
链接到包

POPMUISE
浏览 619回答 1
1回答

慕仙森

您需要<FEATURE>将该指令中的扩展名替换为您希望从下表中启用的扩展名(似乎 README 中有错误,并且sqlite_在示例中删除了前缀;构建标签确实是sqlite_userauth)。因此,启用用户身份验证将是go build -tags "sqlite_userauth".在具有go-sqlite3模块依赖项的项目中,只需确保使用-tags sqlite_userauth.这是一个最小的示例,展示了如何在项目中使用它:mkdir sqlite3authcd sqlite3authgo mod init sqlite3authtouch main.gomain.go:package mainimport (&nbsp; &nbsp; &nbsp; &nbsp; "database/sql"&nbsp; &nbsp; &nbsp; &nbsp; "log"&nbsp; &nbsp; &nbsp; &nbsp; "github.com/mattn/go-sqlite3")func main() {&nbsp; &nbsp; &nbsp; &nbsp; // This is not necessary; just to see if auth extension is enabled&nbsp; &nbsp; &nbsp; &nbsp; sql.Register("sqlite3_log", &sqlite3.SQLiteDriver{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ConnectHook: func(conn *sqlite3.SQLiteConn) error {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("Auth enabled: %v\n", conn.AuthEnabled())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; // This is usual DB stuff (except with our sqlite3_log driver)&nbsp; &nbsp; &nbsp; &nbsp; db, err := sql.Open("sqlite3_log", "file:test.db?_auth&_auth_user=admin&_auth_pass=admin")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer db.Close()&nbsp; &nbsp; &nbsp; &nbsp; _, err = db.Exec(`select 1`)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; }}go mod tidygo: finding module for package github.com/mattn/go-sqlite3go: found github.com/mattn/go-sqlite3 in github.com/mattn/go-sqlite3 v1.14.10# First build with auth extension (-o NAME is just to give binary a name)go build -tags sqlite_userauth -o auth .# then build without itgo build -o noauth ../auth2022/01/27 21:47:46 Auth enabled: true./noauth2022/01/27 21:47:46 Auth enabled: false
随时随地看视频慕课网APP

相关分类

Go
我要回答