1

Why are both handlers called each time I hit the server with a browser. I thought only one or the other would be called according to the book. What am I missing. If I hit url http://localhost:8000/foobar - I am handler is printed twice and if I hit http://localhost:8000/count - I am handler and I am count are both printed.

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// See page 20.
//!+

// Server2 is a minimal "echo" and counter server.
package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var mu sync.Mutex
var count int

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/count", counter)
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    count++
    mu.Unlock()
    fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
    fmt.Println("I am here in handler")
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    fmt.Fprintf(w, "Count %d\n", count)
    mu.Unlock()
    fmt.Println("I am here in counter")
}

//!-
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77
  • 2
    Can you list the requests as seen by your browser? This may be due to the fact that none of your handlers are actually writing a response. – Marc Dec 10 '17 at 23:35
  • 2
    Actually, I wouldn't be surprised if this was the browser looking for the favicon. The best match for that would be `handler`. That would explain the extra response, but that's because it's a whole other request made by the browser. – Marc Dec 10 '17 at 23:38
  • 1
    It's probably a request for `/favicon.ico`. – hobbs Dec 10 '17 at 23:44
  • Yup the favicon - thanks guys `[adrian@stellajay server2]$ ./server2 I am here in handler GET /countjgjhg HTTP/1.1 I am here in handler GET /favicon.ico HTTP/1.1 I am here in counter GET /count HTTP/1.1 I am here in handler GET /favicon.ico HTTP/1.1` – Adrian Cornish Dec 10 '17 at 23:48

1 Answers1

1

As people mentioned in the comments it is the browser requesting the favicon which I proved by printing the GET requests as well

[adrian@stellajay server2]$ ./server2
I am here in handler
GET /countjgjhg HTTP/1.1
I am here in handler
GET /favicon.ico HTTP/1.1

I am here in counter
GET /count HTTP/1.1
I am here in handler
GET /favicon.ico HTTP/1.1
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77