[英]How to write user login error in login page
I'm new one for Golang programming. 我是Golang编程的新手。 In Golang how to display the username error.
在Golang中如何显示用户名错误。 This is my code:
这是我的代码:
func LoginHandler(w http.ResponseWriter, req *http.Request){
if req.Method == http.MethodPost{
un := req.FormValue("username")
p := req.FormValue("password")
u, ok := dbUsers[un]
if !ok{
var body, _ = helpers.LoadFile("sss/login.html")
fmt.Fprintf(response, body)
//fmt.Fprintln(w, "incorrect user name")
//return
}
if u.Password != p{
fmt.Fprintln(w, "incorrect password")
return
}
http.Redirect(w, req, "/index.html", http.StatusSeeOther)
return
}
}
In go You have different ways for error handling 在旅途中您有不同的错误处理方式
func SomeHandler(w http.ResponseWriter, r *http.Request) (int, error) {
if req.Method == http.MethodPost{
un := req.FormValue("username")
p := req.FormValue("password")
u, ok := dbUsers[un]
if !ok{
var body, _ = helpers.LoadFile("sss/login.html")
return 400, errors.New("can't load sss/login")
}
if u.Password != p{
return 400, errors.New("wrong password")
}
http.Redirect(w, req, "/index.html", http.StatusSeeOther)
return 302, nil
}
or 要么
func SomeHandler(w http.ResponseWriter, r *http.Request) {
un := req.FormValue("username")
p := req.FormValue("password")
u, ok := dbUsers[un]
if !ok{
var body, _ = helpers.LoadFile("sss/login.html")
http.Error(w, "can't load sss/login", 400)
return
}
if u.Password != p{
http.Error(w, "wrong password", 400)
return
}
http.Redirect(w, req, "/index.html", http.StatusSeeOther)
return
}
For more information You can read here very helpful blogpost about middlewares: https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/ 有关更多信息,您可以在此处阅读有关中间件的非常有用的博客文章: https ://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/
Post with simple example: https://blog.questionable.services/article/http-handler-error-handling-revisited/ 使用简单示例发布: https : //blog.questionable.services/article/http-handler-error-handling-revisited/
Http package docs: https://golang.org/pkg/net/http/ Http包文档: https : //golang.org/pkg/net/http/
You could do something a little bit more elegant. 您可以做一些更优雅的事情。 Pass a context object to the template and render the error there.
将上下文对象传递给模板,然后在其中呈现错误。
func index(w http.ResponseWriter, r *http.Request) {
context := make(map[string]string]
context["Error"] = "Username error"
t := template.Must(template.ParseFiles("./templates/index.html"))
t.Execute(w, context)
}
Then, on the template render it like this 然后,在模板上像这样渲染它
{{.Error}}}
If no error occurred, the field will be empty. 如果未发生错误,则该字段为空。 Cheers.
干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.