Pass r.Form to another function

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?

1 Like

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

1 Like

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

This seems to give an error:

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

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.
}
3 Likes

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?

1 Like

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.
}
2 Likes

Right on spot! Thank you for your support.

1 Like