Piko Monde
Piko Monde

Reputation: 426

HTML Form Method Post with Golang

So, I have this form in an html. It is intended to have a POST request to /subscribe page:

<html>
  <form action="/subscribe" method="post">
    First Name: <input type="text" name="first_name" placeholder="Willy"/><br/>
    Last Name: <input type="text" name="last_name" placeholder="Warmwood"/><br/>
    Email: <input type="email" name="email" placeholder="[email protected]"/><br/>
    <input type="submit" value="Submit"/>
  </form>
</html>

Then, I have this router in golang:

http.HandleFunc("/subscribe/", SubscribeHandler)

And this handler in golang:

func SubscribeHandler(w http.ResponseWriter, r *http.Request) {
    log.Println(r.Method)
}

But the problem is, it always print GET.

How to post the form, so the value of r.Method is POST?

Thanks

Upvotes: 5

Views: 6172

Answers (1)

dave
dave

Reputation: 64695

Per the docs:

If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash.

Because you registered "/subscribe/", with the trailing slash, it is registered as a subtree. Again, per the docs:

a pattern ending in a slash names a rooted subtree

Because an HTTP redirect is (in practice) always a GET request, the method after the redirect is of course a GET. You can see that a real redirect is happening in this example: https://play.golang.org/p/OcEhVDosTNf

The solution is to either register both:

http.HandleFunc("/subscribe/", SubscribeHandler)
http.HandleFunc("/subscribe", SubscribeHandler)

Or point your form to the one with a /:

<form action="/subscribe/" method="post">

Upvotes: 6

Related Questions