Parsing Input from HTML Forms in Go
Understanding how to parse input from HTML forms is essential when creating dynamic web applications using Go.
Imagine a scenario where you have a simple web application with a form that collects a user's name. When the form is submitted, you want your Go application to receive the submitted name and print a greeting message.
In this example, we'll utilize the Goji framework to handle form submissions:
package main import ( "fmt" "net/http" "github.com/zenazn/goji" "github.com/zenazn/goji/web" ) func hello(c web.C, w http.ResponseWriter, r *http.Request) { r.ParseForm() name := r.PostFormValue("name") fmt.Fprintf(w, "Hello, %s!", name) } func main() { goji.Post("/hello", hello) goji.Serve() }
In this code, the hello function parses the submitted form using r.ParseForm() before accessing the form value associated with the "name" field using r.PostFormValue("name").
To connect your hello.html form with the hello.go code, you need to specify the action attribute in your form to point to the URL where the hello function is defined. Assuming your hello.html looks something like this:
<form action="/hello" method="get"> <input type="text" name="name" /> </form>
When the form is submitted, the browser will send a POST request to the /hello URL, which will be handled by the hello function in your Go application. The function will then parse the form data and print the greeting message based on the submitted name.
The above is the detailed content of How to Parse HTML Form Input in Go?. For more information, please follow other related articles on the PHP Chinese website!