Go - Handling HTML Forms

发布时间 2023-10-17 14:55:47作者: ZhangZhihuiAAA

Problem: You want to process data submitted from HTML forms.


Solution: Use the Form field of http.Request or the FormValue method to access the data submitted from HTML forms.

 

A typical HTML form often looks like this:

< form   action = "/process"   method = "post" > 
    < input   type = "text"   name = "name" /> 
    < input   type = "text"   name = "book" /> 
    < input   type = "submit" /> 
</ form >

Within the <form> tag, you place several HTML form elements including text input, text area, radio buttons, and so on. These elements allow users to enter data to be submitted to the server. Data is submitted to the server when the user clicks a submit button or somehow triggers the form submission. 

The HTML form data is always sent as name - value pairs. The format of the name - value pairs sent through a POST request is specified by the content type of the HTML form. This is defined using the enctype attribute:

< form   action = "/process"   method = "post" enctype = "application/x - www - form - urlencoded" > 
    < input   type = "text"   name = "name" /> 
    < input   type = "text"   name = "book" /> 
    < input   type = "submit" /> 
</ form >

The default value for enctype is application/x - www - form - urlencoded . This means our HTML forms don’t normally need to specify the enctype . Browsers are required to support at least application/x - www - form - urlencoded and multipart/form - data . If you set enctype to application/x - www - form - urlencoded , the browser will encode a long query string in the HTML form data, with the name - value pairs separated by an ampersand (&) and the name separated from the values by an equals sign (=). That’s the same as URL encoding, hence the name. In other words, the HTTP body will look something like this:

name=sau%20sheong&book=go%20cookbook

If you set enctype to multipart/form - data , each name - value pair will be converted into a MIME message part, each with its own content type and content disposition. When would you use one or the other? If you’re sending simple text data, the URL - encoded form is better — it’s simpler and less processing is needed. If you’re sending large amounts of data, the multipart/form - data form is better. 

Now that you know how HTML forms work, take a look at how Go handles HTML forms:

func   main ()   { 
      http . HandleFunc ( "/form" ,   form ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   form ( w   http . ResponseWriter ,   r   * http . Request )   { 
      r . ParseForm () 
      for   k ,   v   :=   range   r . Form   { 
          fmt . Fprintf ( w ,   "%s:  %s\n" ,   k ,   v ) 
      } 
}

Handling HTML forms in Go is pretty straightforward. The Form field of an http.Request is a map of all the form data sent with the request. The keys in the map are the form element names and the values in the map are slices of strings. However, before you start accessing the Form field you need to call the ParseForm method on the http.Request to parse the form data. If you don’t call ParseForm , the Form field will be nil. 

Take a look at this in action. You can use the curl command to send a POST request with the form data to the server:

$  curl  - X  POST  - d  "name=sau  sheong&book=go  cookbook"  http://localhost:8000/form

If you run this on the command line, you will see the following:

name:  [sau  sheong]
book:  [go  cookbook]

If you know exactly what you want from the form, you can actually get the form data even faster. The FormValue method is a convenience method that returns the first value for the named component of the query. If no values are associated with the key, it returns the empty string. If multiple values are associated with the key, it returns the first value:

func   main ()   { 
      http . HandleFunc ( "/form_value" ,   formValue ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   formValue ( w   http . ResponseWriter ,   r   * http . Request )   { 
      fmt . Fprintln ( w ,   r . FormValue ( "name" )) 
}

If you run the same curl command again, you will see the following:

sau  sheong

You might notice that you don’t even need to parse the form data to get the form value. This is because the FormValue method will automatically parse the form data for you.