gpt4 book ai didi

go - 使用带有 martini-go 的 go-http-auth 查询数据库以获得基本身份验证

转载 作者:IT王子 更新时间:2023-10-29 01:55:47 27 4
gpt4 key购买 nike

我正在尝试将 go-http-auth 与 martini-go 一起使用。在此处给出的示例中 - https://github.com/abbot/go-http-auth

package main

import (
auth "github.com/abbot/go-http-auth"
"fmt"
"net/http"
)

func Secret(user, realm string) string {
if user == "john" {
// password is "hello"
return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
}
return ""
}

func handle(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
fmt.Fprintf(w, "<html><body><h1>Hello, %s!</h1></body></html>", r.Username)
}


func main() {
db, err := sql.Open("postgres", "postgres://blabla:blabla@localhost/my_db")
authenticator := auth.NewBasicAuthenticator("example.com", Secret)
m := martini.Classic()
m.Map(db)
m.Get("/users", authenticator.Wrap(MyUserHandler))
m.Run()

}

Secret 函数使用硬编码用户“john”。

我执行时认证成功

curl --user john:hello localhost:3000/users

显然,这是一个带有硬编码用户名和密码的简单示例。

我现在将 Secret 函数改成这个

func Secret(user, realm string) string {

fmt.Println("Executing Secret")

var db *sql.DB

var (
username string
password string
)

err := db.QueryRow("select username, password from users where username = ?", user).Scan(&username, &password)

if err == sql.ErrNoRows {
return ""
}

if err != nil {
log.Fatal(err)
}
//if user == "john" {
//// password is "hello"
//return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
//}
//return ""
return ""

}

但它因 PANIC: runtime error: invalid memory address or nil pointer dereference. 而失败,这显然是因为我试图实例化 var db *sql.DB Secret 函数。我无法将 db *sql.DB 传递给 Secret 函数,因为 auth.BasicNewAuthentication 需要一个 Secret 参数符合 type func (string, string) string

如何正确执行数据库查询并返回密码进行比较?

最佳答案

您可以使用一个简单的闭包将对您的数据库的引用传递给身份验证器函数:

authenticator := auth.NewBasicAuthenticator("example.com", func(user, realm string) string {
return Secret(db, user, realm)
})

...然后更改您的 Secret 以接受数据库作为第一个参数:

func Secret(db *sql.DB, user, realm string) string {
// do your db lookup here…
}

关于go - 使用带有 martini-go 的 go-http-auth 查询数据库以获得基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23006639/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com