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

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行