为什么每次使用浏览器访问服务器时都会调用这两个处理程序。我以为根据书中只会调用其中一个。我错过了什么如果我点击了网址http://localhost:8000/count
- 我是处理程序打印了两次,如果我点击// 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")
}
//!-
- 我是处理程序,我计数都打印。
{{1}}
答案 0 :(得分:0)
正如人们在评论中所提到的那样,浏览器请求了我通过打印GET请求证明的图标
[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