To create and display HTML dropdown select lists in Go, you can use the html/template
package. Here's an example code:
package main
import (
"html/template"
"net/http"
)
type PageData struct {
Options []string
}
func main() {
// Define the select options
options := []string{"Option 1", "Option 2", "Option 3"}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Create a new instance of the PageData struct and pass the options
data := PageData{Options: options}
// Define the HTML template
tmpl := `
<html>
<body>
<form>
<select name="dropdown">
{{range .Options}}
<option value="{{.}}">{{.}}</option>
{{end}}
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
`
// Parse the template
t, err := template.New("dropdown").Parse(tmpl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the template with the PageData
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
http.ListenAndServe(":8080", nil)
}
In this example, we define a PageData
struct to store the select options. We create an HTTP handler function that handles the request and response. Inside the handler function, we define an HTML template using the tmpl
variable. The {{range .Options}}
construct is used to loop over the options and generate the <option>
tags dynamically. Finally, we parse and execute the template, passing the data
variable to provide the options to the template.
You can run this code by saving it to a file, e.g., main.go
, and executing go run main.go
in the terminal. Open your browser and go to http://localhost:8080
to see the HTML dropdown select list with the provided options.