Created
March 29, 2013 14:18
-
-
Save fabioxgn/5271137 to your computer and use it in GitHub Desktop.
Simple data validatio in Go When something goes wrong, the errors and the values filled in by the user are returned back to the template.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Data struct { | |
Cidade model.Cidade | |
Erros template.HTML | |
} | |
func Handler(w http.ResponseWriter, r *http.Request) { | |
data := new(Data) | |
if r.Method == "POST" { | |
r.ParseForm() | |
decoder.Decode(&data.Cidade, r.Form) | |
err := Store.Save(&data.Cidade) | |
if err != nil { | |
data.Erros = template.HTML(strings.Replace(err.Error(), "\n", "<br/>", -1)) | |
} else { | |
http.Redirect(w, r, fmt.Sprintf("/cidade/?Id=", data.Cidade.Id), http.StatusFound) | |
} | |
} | |
err := tmpl.Execute(w, data) | |
} | |
//Template | |
<h1>Cidade</h1> | |
{{.Erros}} | |
<form action="" method="POST"> | |
<input type="text" name="Nome" Value="{{.Cidade.Nome}}"> | |
<input type="text" name="UF" Value="{{.Cidade.UF}}"> | |
<input type="Submit"> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment