Skip to content

Instantly share code, notes, and snippets.

@fabioxgn
Created March 28, 2013 21:40
Show Gist options
  • Save fabioxgn/5267054 to your computer and use it in GitHub Desktop.
Save fabioxgn/5267054 to your computer and use it in GitHub Desktop.
Posting a form in go and returning errors and the form content
type Data struct {
PostData url.Values
Errors string
}
func Handler(w http.ResponseWriter, r *http.Request) {
data := new(Data)
if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
cidade := &model.Cidade{}
//I'm using the gorilla toolkit to decode the form
err = decoder.Decode(cidade, r.Form)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//This will validate the data
err = self.Store.Save(cidade)
if err != nil {
//Here I just try to replace the line breaks to html, but the template engine sanitizes it :(
data.Erros = strings.Replace(err.Error(), "\n", "<br/>", -1)
//Here I get what was posted in the form the send it back
data.PostData = r.Form
} else {
//just a redirect for testing
http.Redirect(w, r, fmt.Sprintf("/cidade/?Id=", cidade.Id), http.StatusFound)
}
}
err := tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
//And in my template I have something like this:
<h1>Cidade</h1>
{{.Erros}}
<form action="" method="POST">
<input type="text" name="Nome" Value="{{.PostData.Nome}}">
<input type="text" name="UF">
<input type="Submit">
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment