Start learning free

LESSON 13 OF 173 · BACKEND: YOUR FIRST API

Your First Route in Go

Practice

A web server is a program that waits for requests and answers them. A browser, or any other program, sends a request: a method, like GET ("give me"), and a path, like / or /products. The server sends back a response: a status code that says how it went, and a body.

In Go, the line app := http.NewServeMux() inside newApp creates your app, and app.HandleFunc teaches it to answer a request. It takes a pattern, the method and the path, and a handler: a function that writes the answer to w:

app.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hi there!")
})

When a GET request for /hello arrives, Go calls the handler and sends back whatever it wrote to w, with the status 200, which means OK. A pattern that ends in / matches every path below it, so the path / alone is written /{$}: {$} means "the path ends here". A path that no pattern matches gets 404 Not Found, with the plain text 404 page not found.

Your app must answer:

GET /          →  200  Welcome to the shop!
GET /products  →  404  404 page not found

Your task: the app is already created for you in newApp. Below app, register a handler for the pattern "GET /{$}" that writes the text "Welcome to the shop!" to w with fmt.Fprint.


Assignment
Follow the Coding Tutorial to register the shop's first route, GET /{$}, and its handler.


Hint
The handler is the second argument of app.HandleFunc, and it takes w http.ResponseWriter and r *http.Request. Go needs no return in it: what you write to w is the answer.


STEP 1 OF 2
    Ctrl + Enter to check

    Shop First Route in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free