Home > Software design >  How to handle multiple POST requests in same handler in golang?
How to handle multiple POST requests in same handler in golang?

Time:12-19

I have two forms in the signup.html file that I want to execute.

  1. The first form redirects to /login but does not insert the data into the database.
  2. The second form neither inserts the data nor does it redirect to the Signup page.

If I set both action equal to the same link then it inserts the data into the database. How to execute multiple POST requests and redirects to multiple pages in a single function?

Thank you!

controllers.go

func Signup(w http.ResponseWriter, r *http.Request) error {
    if r.Method == "GET" {
        return SignupTmpl.Execute(w, nil)
    } else if r.Method == "POST" && http.MethodPost == "Register" {
        register := models.RegisterUser{
            Name:     r.FormValue("name"),
            Email:    r.FormValue("email"),
            Password: r.FormValue("password"),
        }
        values := [3]string{register.Name, register.Email, register.Password}
        database.InsertRegister(values)
        return LoginTmpl.Execute(w, nil)
    } else if r.Method == "POST" && http.MethodPost == "Newsletter" {
        Newsletter(w, r)
        return SignupTmpl.Execute(w, nil)
    }
    return nil
}

signup.html

// Signup form
<form  method="post" action="/login">
    ...
    <input type="submit" value="Register">
</form>

// Newsletter form
<form  method="post" action="/signup">
    ...
    <input type="submit" value="Newsletter">
</form>

CodePudding user response:

http.MethodPost == "Register"
... 
http.MethodPost == "Newsletter"

These comparisons make no sense. http.MethodPost is a constant which contains the verb for HTTP Post requests ("POST"). Constant variables are preferred to hard coded values because unlike a hard coded string, a typeo will cause a compile time error.

<input type="submit" value="Newsletter">

If you want to be able to access the value of this input tag, you need to give it a name:

<input type="submit" name="operation" value="Newsletter">

Then you can check that form value:

if r.Method == "GET" {
   return SignupTmpl.Execute(w, nil)
} else if r.Method == "POST" {
   if r.FormValue("operation") == "Register" {
      ...
   } else if r.FormValue("operation") == "Newsletter" {
      ...
   }
}

I personally would write a different handler for all these operations and then point them at a different URL. Most of your handler logic is routing, and that can be done for free with different handlers. But what you're doing is fine - just make sure :

  1. name input fields you need to refer to later
  2. don't compare 'POST' to 'POST', compare the named input field value to the expected value
  • Related