From cf3fa723ee0cf67c6b1ccee6c8c7d4865a443acd Mon Sep 17 00:00:00 2001 From: bonfy Date: Mon, 10 Sep 2018 14:30:10 +0800 Subject: [PATCH] 04-Web-Form add form backend check --- controller/home.go | 28 ++++++++++++++++++++++++++-- templates/content/login.html | 8 ++++++++ vm/login.go | 6 ++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/controller/home.go b/controller/home.go index 5bea362..ab79471 100644 --- a/controller/home.go +++ b/controller/home.go @@ -1,7 +1,6 @@ package controller import ( - "fmt" "net/http" "github.com/bonfy/go-mega-code/vm" @@ -21,10 +20,18 @@ func indexHandler(w http.ResponseWriter, r *http.Request) { templates[tpName].Execute(w, &v) } +func check(username, password string) bool { + if username == "bonfy" && password == "abc123" { + return true + } + return false +} + func loginHandler(w http.ResponseWriter, r *http.Request) { tpName := "login.html" vop := vm.LoginViewModelOp{} v := vop.GetVM() + if r.Method == http.MethodGet { templates[tpName].Execute(w, &v) } @@ -32,6 +39,23 @@ func loginHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.Form.Get("username") password := r.Form.Get("password") - fmt.Fprintf(w, "Username:%s Password:%s", username, password) + + if len(username) < 3 { + v.AddError("username must longer than 3") + } + + if len(password) < 6 { + v.AddError("password must longer than 6") + } + + if !check(username, password) { + v.AddError("username password not correct, please input again") + } + + if len(v.Errs) > 0 { + templates[tpName].Execute(w, &v) + } else { + http.Redirect(w, r, "/", http.StatusSeeOther) + } } } diff --git a/templates/content/login.html b/templates/content/login.html index ac07a57..f752da5 100644 --- a/templates/content/login.html +++ b/templates/content/login.html @@ -5,4 +5,12 @@

Login

+ + {{if .Errs}} + + {{end}} {{end}} \ No newline at end of file diff --git a/vm/login.go b/vm/login.go index 022087f..2eb091e 100644 --- a/vm/login.go +++ b/vm/login.go @@ -3,6 +3,12 @@ package vm // LoginViewModel struct type LoginViewModel struct { BaseViewModel + Errs []string +} + +// AddError func +func (v *LoginViewModel) AddError(errs ...string) { + v.Errs = append(v.Errs, errs...) } // LoginViewModelOp strutc