This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge
A Web application is an application that can be accessed through the Web. The biggest benefit of a Web application is that it is easy for users to access the application. Users only need to have a browser and do not need to install other software. Web applications are all too common for us in the Internet age. Any language that can develop software to interact with humans will support Web application development.
This series of articles will introduce the Go Web application and practice. Welcome to follow.
The last article focused on a few concepts of how the Web works and some of the mechanics of handling requests. We will continue to analyze the rest of the process of sending and receiving requests, focusing on the parsing of the request body.
Parse the request body
In the vast majority of cases, POST requests are sent through an HTML form, which is an area containing form elements. Form elements (such as text fields, drop-down lists, checkboxes, and so on) are elements that allow the user to enter information into the form. Forms use form labels (
Form is a common tool for us to write Web applications. Through forms, we can easily make the client and server interact with data. The following code shows a login page form:
< HTML >< head> <title></title> </head> <body> <form action="/login" method="post"> </form> </body> </ HTML >Copy the code
We extend the previous example by adding a route to /login, submitting the login information through the login page form, and verifying the login results on the server.
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // Get the method of the request
if r.Method == "GET" {
t, _ := template.ParseFiles("login.tpl")
log.Println(t.Execute(w, nil))}else {
// The logon data is requested, so the logon logic is performed
_ = r.ParseForm()
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
if pwd := r.Form.Get("password"); pwd == "123456" { // Verify that the password is correct
fmt.Fprintf(w, "Welcome aboard, Hello %s!", r.Form.Get("username")) // What is written to w is output to the client
} else {
fmt.Fprintf(w, "Incorrect password, please re-enter!")}}}func sayHelloName(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm() // Parse the parameter passed by the URL and, for POST, the request body.
// Note: If the ParseForm method is not called, the form data cannot be retrieved below
fmt.Println(r.Form) // This information is printed to the server
fmt.Println("path", r.URL.Path)
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello aoho!") // What is written to w is output to the client
}
func main(a) {
http.HandleFunc("/", sayHelloName) // Set the route of access
http.HandleFunc("/login", login)
err := http.ListenAndServe(": 8080".nil) // Set the listening port
iferr ! =nil {
log.Fatal("ListenAndServe: ", err)
}
}
Copy the code
As mentioned earlier, the server implementation first uses the ParseForm() method to parse the form for the request, and then accesses the specific fields of the form.
Submit the form to /login of the server. When the user enters the information and clicks login, it will jump to the server route login. We first need to determine whether it is delivered in POST or GET mode. There is a very simple way to GET the request in the Http package. The request method is r.thod, which returns a string variable, including the GET, POST, and PUT methods.
When we are in the browser open http://127.0.0.1:8080/login, appeared the following interface:
In the login function, we determine whether to display the login page or handle the login logic based on r.method. When a GET request is made, the login page is displayed. When other requests are made, the login logic is processed, such as querying the database and verifying the login information. In the above code, we simply verify that the password string 123456 is a successful login and return the user name. Otherwise, the login fails and the user is prompted. The results are shown in the following two figures:
After entering the user name and the correct password, the submission form returns the corresponding user name.
When the server fails to authenticate the password, it returns a login failure, serving the expectations we set.
summary
This article mainly analyzes the implementation of the request body, through the example of the login page form, submit the login information and verify the login result on the server, so as to introduce the process of parsing the request body. The following articles will continue to cover other processes for analyzing incoming and outgoing requests.
To read the latest articles, follow the public account: AOHO Quest