Pass r.Form to another function


(Sibert) #1

This works:

func index(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()

	for key, values := range r.Form { // range over map
		for _, value := range values { // range over []string
			fmt.Println(key, value)
		}
	}

My question is how do I r.Form this to another function? Like this

mail.Send(r.Form)

How should the receiving function look like?


(Ignacio Gómez) #2

The field Form from http.Request is of the type url.Values, which is just map[string][]string.


(Sibert) #3

Thank you. But how should the receiving function look like?

This seems to give an error:

func Send(form) map[string][]string {

(Ignacio Gómez) #4

That’s not valid Go code. It should look something like this:

func Send(form url.Values) error {
  //Send an email, report an error if something went wrong.
}

(Sibert) #5

Thank you! It seems to be on the right track…, but

func Send(form url.Values) {
	ParseForm(form)

	for key, values := range form { // range over map
		for _, value := range values { // range over []string
			fmt.Println(key, value)
		}
	}

The error: “undefined: ParseForm”. How can I use ParseForm on the form variable?


(Ignacio Gómez) #6

You don’t parse the form in the Send function, your parse it in your handler so that the Form field gets populated and the you pass that Form (which is of type url.Values) to your Send function. So something like this:

func index(w http.ResponseWriter, r *http.Request) {
    // The r.Form field is only available after ParseForm is called so you have to parse first.
	r.ParseForm()
    //Do some form checking or whatever work you need here, then call Send with the values.
    err := mail.Send(r.Form)
    if err != nil {
        //Handle your error.
    }
    //Continue with whatever work you need done.
}

(Sibert) #7

Right on spot! Thank you for your support.