Start learning free

LESSON 149 OF 173 · BACKEND: SHIPPING IT

A Real Web Server: http.Server

Practice

So far the course ran the shop for you. On a server, your program itself is the web server: you build it with go build and run the result. Go's net/http package is made for real traffic, so there's no separate server to install. Each request runs in its own goroutine, so many requests are answered at the same time.

An http.Server holds the server's settings. Addr is the address and the port it listens on: 127.0.0.1 lets only programs on the same machine connect, while 0.0.0.0 means every network interface. Handler is your app: for each request, the server calls its ServeHTTP(w, r). Without one, it uses http.DefaultServeMux, which has none of the shop's routes. ReadTimeout is how long a visitor may take to send a request.

Nothing listens until ListenAndServe() is called. For example, a blog whose routes come from newSite(), reachable only from its own machine, could use:

var blogServer = &http.Server{
    Addr:         "127.0.0.1:9000",
    Handler:      newSite(),
    WriteTimeout: 30 * time.Second,
}

With the shop's full server, the check prints:

$ go build -o shop && ./shop
./shop: your program is the web server; Go's http.Server is made for real traffic
Addr "0.0.0.0:8000": listens on port 8000 of every network interface, so other machines can connect
Handler: every request goes to your app and its routes
ReadTimeout 10s: a visitor has 10s to send the request, then the server closes the connection
Each request runs in its own goroutine, so many requests are answered at the same time (no workers to set)
main: server.ListenAndServe() starts the server, and it answers until the program stops
For each request, the server calls the Handler's ServeHTTP(w, r):
GET / -> 200 OK: The shop is open

Your task: the shop's newApp() and an empty server are already written. Start the server in main with server.ListenAndServe(), then fill in its fields: Handler set to newApp(), Addr set to "0.0.0.0:8000" and ReadTimeout set to 10 seconds.


Assignment
Follow the Coding Tutorial to set up the http.Server that runs the shop on the server, and start it.


Hint
Each field is its name, a colon, the value and a comma. Call newApp() with its parentheses: the Handler is the mux it returns. A duration is a number times time.Second.


STEP 1 OF 4
    Ctrl + Enter to check