How to generate HTML radio buttons and checkboxes in Go forms?

In Go, the form package allows you to generate HTML radio buttons and checkboxes using the Input function. Here is an example of how to generate radio buttons and checkboxes:

  1. Import the net/http and html/template packages:
import ( "net/http" "html/template" )
  1. Define a struct to hold the form data:
type Form struct { Radio string Checkbox []string }
  1. Create a handler function to render the form:
func formHandler(w http.ResponseWriter, r *http.Request) { tmpl := template.Must(template.ParseFiles("form.html")) form := Form{ Radio: "", // default value for radio button Checkbox: []string{}, // default value for checkbox } tmpl.Execute(w, form) }
  1. Create an HTML template file (form.html) to render the form:
<!DOCTYPE html> <html> <head> <title>Form</title> </head> <body> <form action="/" method="post"> <p>Radio buttons:</p> <label><input type="radio" name="Radio" value="option1" {{if eq .Radio "option1"}}checked{{end}}> Option 1</label><br> <label><input type="radio" name="Radio" value="option2" {{if eq .Radio "option2"}}checked{{end}}> Option 2</label><br> <label><input type="radio" name="Radio" value="option3" {{if eq .Radio "option3"}}checked{{end}}> Option 3</label><br> <p>Checkboxes:</p> <label><input type="checkbox" name="Checkbox" value="option1" {{if contains .Checkbox "option1"}}checked{{end}}> Option 1</label><br> <label><input type="checkbox" name="Checkbox" value="option2" {{if contains .Checkbox "option2"}}checked{{end}}> Option 2</label><br> <label><input type="checkbox" name="Checkbox" value="option3" {{if contains .Checkbox "option3"}}checked{{end}}> Option 3</label><br> <input type="submit" value="Submit"> </form> </body> </html>
  1. Create a handler function to process the form submission:
func submitHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Println("Radio:", r.FormValue("Radio")) fmt.Println("Checkbox:", r.Form["Checkbox"]) // Handle form submission here }
  1. Define the main function and set up the server to handle the form request:
func main() { http.HandleFunc("/", formHandler) http.HandleFunc("/submit", submitHandler) http.ListenAndServe(":8080", nil) }

Now when you run the program and navigate to http://localhost:8080, you should see a form with radio buttons and checkboxes. You can select options and submit the form to see the selected values in the console output.