Skip to content

Instantly share code, notes, and snippets.

@fabioxgn
Created March 29, 2013 14:18
Show Gist options
  • Select an option

  • Save fabioxgn/5271137 to your computer and use it in GitHub Desktop.

Select an option

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.
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