How to get send value from request object
I am trying to make a POST request form with two different submit buttons. I would like to try and get the value of a submit button in go. How do I get this from the http.Request object.
HTML code:
<form action="/save" method="POST">
<div><span>Title: </span><textarea name="title" placeholder="Link">{{printf "%s" .Title}}</textarea></div>
<div>
<button type="submit" value="submit1">1</button>
<button type="submit" value="submit2">2</button>
</div>
</form>
GO code:
func saveHandler(w http.ResponseWriter, r *http.Request) {
... How do I get the submit value
title := r.FormValue("title")
fmt.Println(title)
}
func main() {
http.HandleFunc("/", viewHandler)
http.HandleFunc("/save", saveHandler)
http.ListenAndServe(":8080", nil)
}
Or do I need to do some Ajax trick where I have a hidden field and set it in ajax before submitting?
+3
source to share
1 answer
Give your buttons an attribute name
and then you can differentiate between them.
HTML:
<form action="/save" method="POST">
<div><span>Title: </span><textarea name="title" placeholder="Link">{{printf "%s" .Title}}</textarea></div>
<div>
<button type="submit" value="submit1" name="submit">1</button>
<button type="submit" value="submit2" name="submit">2</button>
</div>
</form>
Go:
submit := r.FormValue("submit") // will be "submit1" or "submit2"
+1
source to share