Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用go http auth和martini go查询数据库中的基本身份验证_Go_Basic Authentication_Martini - Fatal编程技术网

使用go http auth和martini go查询数据库中的基本身份验证

使用go http auth和martini go查询数据库中的基本身份验证,go,basic-authentication,martini,Go,Basic Authentication,Martini,我正在尝试将go http auth与martini go一起使用。在这里给出的示例中- 显然,这是一个带有硬编码用户名和密码的简单示例 我现在把秘密函数改成这个 func Secret(user, realm string) string { fmt.Println("Executing Secret") var db *sql.DB var ( username string password string )

我正在尝试将go http auth与martini go一起使用。在这里给出的示例中-

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

我现在把秘密函数改成这个

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 ""

}
但它失败的原因是:运行时错误:无效内存地址或零指针取消引用。这显然是因为我试图在Secret函数中实例化var db*sql.db。我无法将db*sql.db传递给Secret函数,因为auth.BasicNewAuthentication需要一个符合func string、string string类型的Secret参数


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

您可以使用简单的闭包将对数据库的引用传递给authenticator函数:

authenticator := auth.NewBasicAuthenticator("example.com", func(user, realm string) string {
    return Secret(db, user, realm)
})
…然后更改密码以接受数据库作为第一个参数:

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

您可以使用简单的闭包将对DB的引用传递给authenticator函数:

authenticator := auth.NewBasicAuthenticator("example.com", func(user, realm string) string {
    return Secret(db, user, realm)
})
…然后更改密码以接受数据库作为第一个参数:

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

阿提拉斯回答的替代方法。您可以定义一个结构,在其上定义秘密处理程序,并仅将引用的函数go将对所有者的引用传递给authhandler


阿提拉斯回答的替代方法。您可以定义一个结构,在其上定义秘密处理程序,并仅将引用的函数go将对所有者的引用传递给authhandler


谢谢这很有道理,谢谢。现在这很有道理。
type SecretDb struct {
  db *DB
}
func (db *SecretDb) Secret(user, realm string) string {
 // .. use db.db here
}


func main() {
   secretdb = SecretDb{db}
   ...
   auth.NewBasicAuthenticator("example.com", secretdb.Secret)
   ...
}