Chapter 15 - Web Apps
Exercise 1: A Simple Web App
Here’s the start of a web app that simulates rolling a six-sided die. When a browser makes a request for the /roll
path, the app will respond with a random number from 1 to 6. Each refresh of the page will generate a new random number.
- Within
rollHandler
:- Call
rollDie
. - Convert the return value to a
string
. You may want to consult the documentation for the"strconv"
package’sItoa
function. - Convert the string to a slice of bytes, and store it in a variable named
body
. We’ve already set up code that will take that variable and write its contents to the response.
- Call
- Within
main
, set up therollHandler
function to handle all requests with a path of"/roll"
. See the documentation for the"net/http"
package’sHandleFunc
function.
When you’re ready, have a look at our solution.
Exercise 2: Query Parameters
URLs can include a “query” at the end with various parameters and corresponding values. For example:
http://example.com/?one=a&two=b
This query has two parameters. The one
parameter has a value of a
, and the two
parameter has a value of b
.
We’ve set up a getParameter
function for you, which can read the value of a query parameter. Here’s how it works:
- Every HTTP handler function receives a pointer to an
http.Request
value. - That
Request
has aURL
field which holds a"net/url"
URL
value. - That
URL
value has aQuery
method which returns a map with the query parameters.
Your task is to use getParameter
in a web app. You’ll be writing a request handler function that takes a query parameter and displays it as an HTML <h1>
heading.
- Set up a handler function that can be passed to http.HandleFunc (that is, it must accept http.ResponseWriter and *http.Request parameters).
- Within the function, call
getParameter
to get the value of the “text” parameter. - Write the returned string out the the response in an <h1> HTML tag.
- Within the function, call
- Within
main
:- Set up your function to handle requests for the “/big” path.
- Then start an HTTP server on port 8080.
This is a lot to do from memory; don’t hesitate to look at prior examples as a guide!
When you’re done, start your app and try visiting these URLs:
http://localhost:8080/big?text=Hello
http://localhost:8080/big?text=Head%20First%20Go
http://localhost:8080/big?text=Your%20Name%20Here
Here’s our solution.