40. From Go to the web — Homework solutions

The .go solution files are in exercises/40/homework/solutions/. Each one is a server: run it, open the address in a browser, and stop it with Ctrl + C.

Problem 1 — Your own reply

Problem. Reply with two lines of text.

How to think about it. fmt.Fprintln adds a line ending, just as fmt.Println does. So two calls make two lines. Nothing else in the file needs to change. Stop the old server and start it again, or you will see the old text.

Worked solution.

package main

import (
    "fmt"
    "net/http"
)

func handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Keiko")
    fmt.Fprintln(w, "Fried rice")
}

func main() {
    http.HandleFunc("/", handleHome)

    fmt.Println("Server running at http://localhost:8080")
    fmt.Println("Press Ctrl+C to stop it.")

    err := http.ListenAndServe("localhost:8080", nil)
    if err != nil {
        fmt.Println("Server stopped:", err)
    }
}

Common mistakes.

  • Changing the code and reloading the browser without restarting the server. The running program does not read your file again.
  • Writing fmt.Println("Keiko"). It compiles, and the text goes to the terminal, not to the browser. The browser gets an empty page.

Problem 2 — Another port

Problem. Listen on port 8081.

How to think about it. The port is written in the ListenAndServe call. The printed message is only text, so Go will not correct it for you. It must be changed as well. The Challenge shows how to stop writing it twice.

Worked solution.

package main

import (
    "fmt"
    "net/http"
)

func handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello from port 8081!")
}

func main() {
    http.HandleFunc("/", handleHome)

    fmt.Println("Server running at http://localhost:8081")
    fmt.Println("Press Ctrl+C to stop it.")

    err := http.ListenAndServe("localhost:8081", nil)
    if err != nil {
        fmt.Println("Server stopped:", err)
    }
}

With this running, http://localhost:8081 shows the page, and http://localhost:8080 gives a connection error in the browser, because nothing is listening there.

Common mistakes.

  • Changing only the message, or only the ListenAndServe call. The first still listens on 8080, and the second prints the wrong address.

Problem 3 — Echo the path

Problem. Reply with the method and the path.

How to think about it. Both are in the request, so they come from r. fmt.Fprintf works like fmt.Printf, with w first. The pattern "/" matches every path, so one handler sees all of them.

Worked solution.

package main

import (
    "fmt"
    "net/http"
)

func handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s %s\n", r.Method, r.URL.Path)
}

func main() {
    http.HandleFunc("/", handleHome)

    fmt.Println("Server running at http://localhost:8080")
    fmt.Println("Press Ctrl+C to stop it.")

    err := http.ListenAndServe("localhost:8080", nil)
    if err != nil {
        fmt.Println("Server stopped:", err)
    }
}

With curl.exe -i http://localhost:8080/some/page, the body is:

GET /some/page

Common mistakes.

  • Writing r.Path. The path is inside the URL, so it is r.URL.Path. Go stops with r.Path undefined.
  • Forgetting \n at the end of the format. It still works, but the line has no ending.

Challenge — A clear start error

Problem. Put the address in a constant, and print a clear message when the server cannot start.

How to think about it. The address is one fact that appears in several places, which is what a constant is for. ListenAndServe returns only on failure, so the code inside the if is the right place for the message. Keep printing the error itself: your guess about the cause may be wrong, and the error says what really happened.

Worked solution.

package main

import (
    "fmt"
    "net/http"
)

const address = "localhost:8080"

func handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello from Go!")
}

func main() {
    http.HandleFunc("/", handleHome)

    fmt.Println("Server running at http://" + address)
    fmt.Println("Press Ctrl+C to stop it.")

    err := http.ListenAndServe(address, nil)
    if err != nil {
        fmt.Println("Could not start the server on " + address + ".")
        fmt.Println("Is another copy still running?")
        fmt.Println(err)
    }
}

With another copy running, the second one prints:

Server running at http://localhost:8080
Press Ctrl+C to stop it.
Could not start the server on localhost:8080.
Is another copy still running?
listen tcp 127.0.0.1:8080: bind: address already in use

On Windows, the last line is worded differently after bind:.

Common mistakes.

  • Replacing the error with your own message, and not printing it. If the real cause is something else, nobody can tell.
  • Writing const address := "localhost:8080". A constant uses =, and it can sit outside the functions. := works only inside a function.