Handling Multiple Submit Buttons in Go

When a form has multiple buttons that perform different server-side actions (e.g., "Save Draft" vs. "Save & Continue"), you can distinguish them in your Go backend using the native HTML name and value attributes.

1. The HTML Pattern

Give all submit buttons the same name, but unique value attributes. Only the button that was actually clicked will be included in the POST request.

<form action="/incidents/save" method="POST">
  <!-- Form Fields -->
  <input type="text" name="title" placeholder="Incident Title">

  <!-- Action Buttons -->
  <button type="submit" name="form_action" value="save">
    Save Draft
  </button>

  <button type="submit" name="form_action" value="navigate">
    Save & Add Team
  </button>
</form>

2. The Go Backend Logic

In your controller, use r.FormValue() to check which button triggered the submission.

func (c *Controller) HandleSave(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseForm(); err != nil {
        http.Error(w, "Bad Request", http.StatusBadRequest)
        return
    }

    // Identify the action
    action := r.FormValue("form_action")

    switch action {
    case "save":
        // Logic for "Save Draft"
        saveToDB(r.PostForm)
        http.Redirect(w, r, "/current-page", http.StatusSeeOther)

    case "navigate":
        // Logic for "Save & Add Team"
        saveToDB(r.PostForm)
        http.Redirect(w, r, "/next-step-url", http.StatusSeeOther)

    default:
        // Fallback for 'Enter' key submissions
        saveToDB(r.PostForm)
    }
}

Why use this?