Skip to content
Permalink
Browse files

04-Web-Form add form backend check

  • Loading branch information...
bonfy committed Sep 10, 2018
1 parent f6e6b27 commit cf3fa723ee0cf67c6b1ccee6c8c7d4865a443acd
Showing with 40 additions and 2 deletions.
  1. +26 −2 controller/home.go
  2. +8 −0 templates/content/login.html
  3. +6 −0 vm/login.go
@@ -1,7 +1,6 @@
package controller

import (
"fmt"
"net/http"

"github.com/bonfy/go-mega-code/vm"
@@ -21,17 +20,42 @@ 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)
}
if r.Method == http.MethodPost {
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)
}
}
}
@@ -5,4 +5,12 @@ <h1>Login</h1>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p><input type="submit" name="submit" value="Login"></p>
</form>

{{if .Errs}}
<ul>
{{range .Errs}}
<li>{{.}}</li>
{{end}}
</ul>
{{end}}
{{end}}
@@ -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

0 comments on commit cf3fa72

Please sign in to comment.
You can’t perform that action at this time.