如何在登录页面中写入用户登录错误

时间:2019-07-05 10:11:42

标签: go

我是Golang编程的新手。在Golang中如何显示用户名错误。 这是我的代码:

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

2 个答案:

答案 0 :(得分:0)

使用中,您有不同的错误处理方式

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
}

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
}

有关更多信息,您可以在此处阅读有关中间件的非常有用的博客文章: How to add multiple values to a dictionary key in python?

以简单的示例发布: https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/

Http包文档:https://blog.questionable.services/article/http-handler-error-handling-revisited/

答案 1 :(得分:0)

您可以做一些更优雅的事情。 将上下文对象传递给模板,然后在其中呈现错误。

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)
}

然后,在模板上像这样渲染它

{{.Error}}}

如果未发生错误,则该字段为空。 干杯。