15. HTTP Servers
Activity 15.01: Adding a Page Counter to an HTML Page
Solution:
- First, we import the necessary packages:
package main import ( "fmt" "log" "net/http" )
- Here, "
net/http
" is the usual package for http communication, "log
" is the package for logging (in this case to the standard output), and "fmt
" is the package used to format input and output. This can be used to send messages to the standard output, but we use it here just as a message formatter. - We define here a type called
PageWithCounter
, which represents our handler, can count visits, and has a heading and some content for the page. The counter will increase every time the page loads:type PageWithCounter struct{ counter int heading string content string } func(h *PageWithCounter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
This is the standard handler function for any struct implementing the
http.Handler
interface. Note...