This is the 5th day of my participation in the August More Text Challenge

Web application is a kind of application that can be accessed through the Web. The biggest advantage of Web application is that users can easily access the application. Users only need to have a browser and do not need to install other software. Web applications are too common for us in the Internet age. Any language that can develop software that interacts with humans is bound to support Web application development.

This series of articles will introduce Go Web applications and practices. Welcome to follow.

The previous article focused on other processes for sending and receiving requests, with emphasis on parsing the request body. This article describes the process of returning the response body.

The tissue returns the response body

After the server processes the request, how does it send the specified content as a response to the client? As you saw in the example in the previous article, we are using the ResponseWriter interface, through which the processor can create an HTTP response. The ResponseWriter interface has the following three methods:

type ResponseWriter interface {

	Header() Header

	Write([]byte) (int, error)

	WriteHeader(statusCode int)
}
Copy the code
  • Write: receives a byte array as an argument and writes the byte array to the body of the HTTP response. If the first 512 bytes of the response are not set when the Write operation is performed, the content type of the response is determined by the first 512 bytes written.
  • WriteHeader method: accepts an integer representing the HTTP response status code as a parameter and uses this integer as the return status code of the HTTP response; After calling this method, the user can apply theResponseWriterWrite, but cannot write anything to the head of the response. If the user has not executed the WriteHeader method before calling the Write method, 200 (OK) is used as the status code for the response by default.
  • Using the Header method, you can retrieve a Header mapping, modify the mapping to modify the Header, and the modified Header will be included in the HTTP response and sent to the client along with the response.

Let’s use a concrete example to demonstrate how to apply the three methods of the ResponseWriter interface to organize the response of the client.

import (
	"encoding/json"
	"log"
	"net/http"
)

type User struct {
	Name    string
	Habits []string
}

func write(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type"."application/json")
	w.Header().Set("X-Custom-Header"."custom") // Set a custom header
	w.WriteHeader(201) // Set the status code for creating a user
	user := &User{
		Name:    "aoho",
		Habits: []string{"balls"."running"."hiking"},
	}
	json, _ := json.Marshal(user)
	w.Write(json) // Write the user who created the result
}

func main(a) {
	http.HandleFunc("/write", write)         // Set the access route
	err := http.ListenAndServe(": 8080".nil) // Set the listening port
	iferr ! =nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Copy the code

In the example above, we constructed the result of the response after successfully creating the user. As shown in the code above, we first set the content-Type header of the response to Application /json, and set the custom header (as needed in the actual application). Set the response status code after the user is created to 201 (201 indicates successful creation). The Body of the response is constructed as the created User information, including the User name and interests. The result of the request is shown in the following two figures.

We simulate the Post request, visit http://127.0.0.1:8080/write, response status code of 201, the Body to create a successful return to the User information.

The header information returned is shown in the figure above, including the content-Type and the custom header, as expected.

summary

This article mainly analyzes the implementation of the return response body, through a concrete example to demonstrate how to apply the three methods of the ResponseWriter interface to organize the response of the client. Now that the basics of HTTP are covered, the following articles will dive into the introduction and practice of the Go Web popular framework.

Read the latest article, pay attention to the public number: AOHO Qiusuo