我想做什么
注册过程成功后,我想重定向到索引页面。
有什么问题
填满用户名和密码后,页面不会重定向到索引页面,而仅停留在signup.html。
我做了什么
我怀疑createUser函数返回nil并导致错误,但我无法解决。
代码
// User model declaration
type User struct {
gorm.Model
Username string `form:"username" binding:"required" gorm:"unique;not null"`
Password string `form:"password" binding:"required"`
}
// User sign up
func createUser(username string, password string) []error {
passwordEncrypt, _ := crypto.PasswordEncrypt(password)
db := gormConnect()
defer db.Close()
// Insert
if err := db.Create(&User{Username: username, Password: passwordEncrypt}).GetErrors(); err != nil {
return err
}
return nil
}
func main(){
router := gin.Default()
router.LoadHTMLGlob("front/*.html")
dbInit()
// index
router.GET("/", func(c *gin.Context) {
b_models := dbGetAll()
num := dbGetNum()
sumQuantity := dbGetSumQuantity()
sumPrice := dbGetSumPrice()
c.HTML(200, "belongings.html", gin.H{"b_models": b_models, "num": num, "sumQuantity": sumQuantity.Totalquantity, "sumPrice": sumPrice.Totalprice})
})
// User sign up page
router.GET("/signup", func(c *gin.Context) {
c.HTML(200, "signup.html", gin.H{})
})
// User sign up process
router.POST("/signup", func(c *gin.Context) {
var form User
// Validation
if err := c.Bind(&form); err != nil {
c.HTML(http.StatusBadRequest, "signup.html", gin.H{"err": err})
log.Println("fail to login because your info is invalid")
c.Abort()
} else {
username := c.PostForm("username")
password := c.PostForm("password")
// Process to reject duplicate registered users
if err := createUser(username, password); err != nil {
c.HTML(http.StatusBadRequest, "signup.html", gin.H{"err": err})
c.Abort()
} else {
log.Println("success to signup!")
c.Redirect(302, "/")
}
}
})
}
最佳答案
您可以在javascript中更改页面,但我不明白您为什么要您的后端执行前端工作。
window.location.href = "the_page.html"
关于go - 如何重定向到另一个网页,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/66078714/