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.

package main

import (
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

// rollDie simulates rolling a six-sided die.
func rollDie() int {
	return rand.Intn(6) + 1
}

func rollHandler(writer http.ResponseWriter, request *http.Request) {
	// YOUR CODE HERE: Call rollDie, convert the return
	// value to a string, and convert the string to a
	// slice of bytes. Store the result in a "body"
	// variable.
	
	_, err := writer.Write(body)
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	rand.Seed(time.Now().Unix())
	// YOUR CODE HERE: Have all requests for a URL with a
	// path of "/roll" go to the rollHandler function.
	
	err := http.ListenAndServe("localhost:8080", nil)
	log.Fatal(err)
}

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:

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 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:

package main

import (
	"log"
	"net/http"
)

// getParameter returns the first value associated with a
// named query parameter from an http.Request.
func getParameter(request *http.Request, parameterName string) string {
	query := request.URL.Query()
	return query[parameterName][0]
}

// YOUR CODE HERE: Set up a handler function.

func main() {
	// YOUR CODE HERE: Set up your function to handle
	// requests for the "/big" path.
	// Then start an HTTP server on port 8080.
}

Here’s our solution.