gpt4 book ai didi

http - 我正在努力将 id 从 mysql 附加到 URL

转载 作者:数据小太阳 更新时间:2023-10-29 03:08:56 27 4
gpt4 key购买 nike

我正在尝试向 url 附加一个 id(和其他信息),以便稍后访问它,但经过一番研究后我找不到正确的方法。

我试过使用 Get() 方法、query()、Add(),但无法重定向 URL。

var email_ployer string

func RegisterNewPloyer(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/ployer/register" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
db := connect.ConnectDB()
defer db.Close()
switch r.Method {
case "POST":
email_ployer = r.FormValue("email")
senha := r.FormValue("senha")
senha, _ = HashPassword(senha)
tx, _ := db.Begin()
stmt, _ := tx.Prepare("INSERT INTO ployers(email_ployer, senha_ployer) VALUES(?,?)")
_, erro := stmt.Exec(email_ployer, senha)
if erro != nil {
tx.Rollback()
log.Fatal(erro)
}
tx.Commit()
}
Redirect(w, r)
}

func Redirect(w http.ResponseWriter, r *http.Request) {
db2 := connect.ConnectDB()
defer db2.Close()
var id string
tx, _ := db2.Begin()
rows, _ := tx.Query("SELECT id FROM ployers WHERE email_ployer = '?'", email_ployer)
for rows.Next() {
if err := rows.Scan(&id); err != nil {
log.Fatal(err)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
http.Redirect(w, r, x, http.StatusSeeOther)
}




func main() {
http.HandleFunc("/ployer/seja-um-de-nos", LoadPloyerContent)
http.HandleFunc("/ployer/register", register.RegisterNewPloyer)
http.HandleFunc("/ployer/complete/", LoadPloyerContent)
http.HandleFunc("/ployer/register-received", LoadPloyerContent)
log.Fatal(http.ListenAndServe(":3306", nil))
}

在我的系统中,我希望用户注册他的电子邮件和密码,在数据库中创建一个新用户并将 URL 重定向到类似 localhost:3306/ployer/complete/id 的地方

最佳答案

只需使用 res.LastInsertId() 获取 id 并将其传递给您的重定向函数,然后构建 url:

func RegisterNewPloyer(w http.ResponseWriter, r *http.Request) {
//...
//...
res, erro := stmt.Exec(email_ployer, senha)
if erro != nil {
tx.Rollback()
log.Fatal(erro)
}
tx.Commit()
id, erro := res.LastInsertId()
if erro != nil {
log.Fatal(erro)
}
Redirect(w, r, id)
}

func Redirect(w http.ResponseWriter, r *http.Request, id int64) {
uri := fmt.Sprintf("http://localhost:3306/ployer/complete/%d", id)
http.Redirect(w, r, uri, http.StatusSeeOther)
}

关于http - 我正在努力将 id 从 mysql 附加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55801880/

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