1. Dobrosław Żybort
  2. PastebinGo

Commits

Dobrosław Żybort  committed 872c3d2

Decode all forms to struct

  • Participants
  • Parent commits cda6243
  • Branches default

Comments (0)

Files changed (4)

File handlersPaste.go

View file
 
 import (
 	//"fmt"
+	"github.com/gorilla/schema"
 	"net/http"
 	"strconv"
 )
 
 func addPaste(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
 	paste := NewPaste()
-	if req.FormValue("title") != "" {
-		paste.Title = req.FormValue("title")
+	req.ParseForm()
+	pasteData := new(PasteForm)
+	schema.NewDecoder().Decode(pasteData, req.Form)
+	if pasteData.Title != "" {
+		paste.Title = pasteData.Title
 	}
 
-	paste.Data = req.FormValue("code")
+	paste.Data = pasteData.Data
 	if paste.Data == "" {
 		http.Redirect(wri, req, reverse("index"), http.StatusNoContent)
 		return
 	}
 
 	if ctx.User == nil {
-		if req.FormValue("name") != "" {
-			paste.Author = req.FormValue("name")
+		if pasteData.Author != "" {
+			paste.Author = pasteData.Author
 		}
 	} else {
 		paste.Author = ctx.User.Name

File handlersUser.go

View file
 }
 
 func login(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
-	username, password := req.FormValue("username"), req.FormValue("password")
+	req.ParseForm()
+	userData := new(UserForm)
+	schema.NewDecoder().Decode(userData, req.Form)
 
-	user, err := userLogin(username, password, ctx)
+	user, err := userLogin(userData.Name, userData.Password, ctx)
 	if err != nil {
 		ctx.Session.AddFlash("Invalid username/password")
 		return loginForm(wri, req, ctx)
 func register(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
 	req.ParseForm()
 	userData := new(UserForm)
-	decoder := schema.NewDecoder()
-	decoder.Decode(userData, req.Form)
+	schema.NewDecoder().Decode(userData, req.Form)
 	if userData.Password != userData.PasswordSecond {
 		ctx.Session.AddFlash("Passwords not match")
 		return registerForm(wri, req, ctx)

File paste.go

View file
 	DisplayDatetime string
 }
 
+type PasteForm struct {
+	Title  string `schema:"title"`
+	Data   string `schema:"code"`
+	Author string `schema:"username"`
+}
+
 //=============================================================================
 
 func NewPaste() *Paste {

File templates/index.html

View file
 		{{ if .ctx.User }}
 			{{ .ctx.User.Name }}
 		{{ else }}
-			<input type="text" name="name">
+			<input type="text" name="username">
 		{{ end }}
 		</p>
 		<p><button>Submit</button></p>