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:
net/http
and html/template
packages:import (
"net/http"
"html/template"
)
type Form struct {
Radio string
Checkbox []string
}
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)
}
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>
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
}
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.