“This is the 13th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
So far, almost all of our Go primer articles have been running on a terminal.
The code or application running on the terminal is only suitable for its own use in the context of the environment. That said, if the user doesn’t have the Go environment installed, there’s no way to run the Go code we’ve written. The average user has been spoiled by the Internet and the World Wide Web and doesn’t want to learn to use a terminal in order to use your application.
What’s more, you don’t want to install any extra clients and applications on your phone. What they want to solve in the browser can be solved in the browser, click a link or scan a QR code to use. This is probably the design concept of applets – ready-to-go, no installation required.
Write Web applications using Go
We run the Go language on the terminal like this:
# yuzhou_1su @ RaindeMacBook-Pro in ~/GoProjects [22:23:34]
$ go run hello.go
hello, world
Copy the code
Running a Go program on the Web might look something like this:
Net/HTTP packet
Go provides a very convenient built-in HTTP package that covers the implementation of the HTTP client and server side. Using the NET/HTTP package, we can easily write programs for HTTP clients or servers.
What is HTTP?
HyperText Transfer Protocol (HTTP) is the most widely used network Protocol on the Internet. It defines the transmission standards for requests and responses between clients and servers. This protocol can be used to easily and quickly communicate between Web browsers and Web servers.
More details will come when I write about the HTTP protocol, but for now it’s just a brief overview.
A simple Web application
Processing requests from browsers would have required a lot of work:
- Receive requests from the browser
- Responds to a browser request
Let’s create a new main.go file and write the following code:
package main
import (
"log"
"net/http"
)
func viewHandler(writer http.ResponseWriter, request *http.Request) {
message := []byte("Hello, World!")
_, err := writer.Write(message)
iferr ! =nil {
log.Fatal(err)
}
}
func main(a) {
http.HandleFunc("/hello", viewHandler)
err := http.ListenAndServe("localhost:8800".nil)
log.Fatal(err)
}
Copy the code
Running the above code in a terminal gives us a Web application of our own:
$ go run main.go
Copy the code
At this time will not see any output in the terminal, but if by opening the browser, enter the server listening address: http://localhost:8800/hello
This sends a request to our small Web server on behalf of the browser, and the server responds with a “Hello, World!” In response.
If, at this point, we open another browser and type in the same url, the server will listen for the request until we stop the server running on the terminal, for example by using CTRL+C to exit our main.go function:
$ go run main.go
^Csignal: interrupt
(base)
Copy the code
Refresh the url at this point, and further access will be rejected, as shown below:
Code interpretation
We can start with the main function:
http.HandleFunc("/hello", viewHandler)
Using strings/hello
callhttp.HandleFunc
, and then calledviewHandler
Function, which tells the application whenever it receives a/hello
The trailing URL request is calledviewHandler
function- call
http.ListenAndServe("localhost:8800", nil)
To start the Web server, the string passed in"localhost:8800"
Indicates that only requests from port 8800 on your own machine are accepted. Second parameternil
The value simply means that the function set by HandleFunc will be used to process the request later. - If the server does not encounter an error, it will continue to run until it encounters an exit, and the program logs the error and prints it as an error log:
log.Fatal(err)
Then let’s look at the viewHandler function:
func viewHandler(writer http.ResponseWriter, request *http.Request)
- Server to the
viewHandler
Pass ahttp.ResponseWriter
Is used to write data to the browser response - It also receives a point
http.Request
Pointer that represents the browser request ResponseWriter
Writer does not accept strings, but it can receive bytes worth slicing, so in the messagemessage := []byte("Hello, World!" )
The string “Hello, World! convert[]byte
- And then it will convert to good
message
Passed to the Writer - The Writer method of ResponseWriter returns the number of bytes successfully written, as well as any errors encountered, and we can’t do anything useful with the number of bytes written, so ignore it. If an error occurs, it is logged and the program exits.
conclusion
The first thing a Web application needs to do is be able to respond when the browser sends a request to the Web server.
Go language provides a very convenient NET/HTTP package to simplify procedural operations, so that we do not need to write any underlying code can achieve a simple Web application.
But we certainly don’t stop there, and a feature-rich Web server does more than just provide a “Hello, World!” But we can learn about Web development in the simplest way.
In future articles, we will be able to learn more about Go Web development, which is the author’s direction. See you next
Reference article: Head First Go: 15 Responding to requests