duangonglian6028 2017-12-10 23:28
浏览 10
已采纳

为什么两个HTTP处理程序都被称为[重复]

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
", 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
", count)
    mu.Unlock()
    fmt.Println("I am here in counter")
}

//!-
</div>
  • 写回答

1条回答 默认 最新

  • drnrxv9383 2017-12-10 23:50
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备