Skip to content

Commit

Permalink
04-Web-Form add form backend check
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Sep 10, 2018
1 parent f6e6b27 commit cf3fa72
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
28 changes: 26 additions & 2 deletions controller/home.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package controller

import (
"fmt"
"net/http"

"github.com/bonfy/go-mega-code/vm"
Expand All @@ -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)
}
}
}
8 changes: 8 additions & 0 deletions templates/content/#.html
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
6 changes: 6 additions & 0 deletions vm/#.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cf3fa72

Please # to comment.