How to create HTML forms and handle form submissions in Go?

To create HTML forms and handle form submissions in Go, you can follow these steps:

  1. Create a Go web server: Start by creating a basic Go web server using the net/http package.
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", home) http.HandleFunc("/submit", submit) http.ListenAndServe(":8080", nil) } func home(w http.ResponseWriter, r *http.Request) { // Serve the HTML form page fmt.Fprint(w, ` <html> <body> <form action="/submit" method="post"> <input type="text" name="name" placeholder="Name"> <input type="email" name="email" placeholder="Email"> <input type="submit" value="Submit"> </form> </body> </html> `) } func submit(w http.ResponseWriter, r *http.Request) { // Handle the form submission name := r.FormValue("name") email := r.FormValue("email") fmt.Fprintf(w, "Name: %s\nEmail: %s", name, email) }
  1. Serve the HTML form page and handle form submission: In the code above, we define two handler functions - home and submit. The home function serves the HTML form page when the root URL is accessed. The submit function handles the form submission when the form is submitted.

  2. Extract form data: In the submit handler, you can extract the form data using the r.FormValue function. By passing the name attribute of the input field as an argument, you can retrieve its value.

  3. Process and display the submitted data: After extracting the form data, you can process it as needed. In the example above, the submitted name and email are displayed as a response.

  4. Run the Go web server: Save the file with a .go extension and run it using the go run command. Access your web server at http://localhost:8080 and submit the form to see the submitted data displayed on the page.

This is a simple example to get you started with handling HTML form submissions in Go. You can build upon this foundation to add validation, database integration, or any other functionality required for your specific use case.