为什么http.HandleFunc对一个请求执行两次?

时间:2019-08-09 06:33:46

标签: go webserver net-http

我用golang构建了一个非常简单的Web服务器,以了解http包,但是我发现HandleFunc函数针对一个请求执行了两次,并且出现了一个favicon.ico,我没想到。

这是Web服务器代码:

package main

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

// sayHelloName a basic web function
func sayHelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() // Parse parameters
    fmt.Println(r.Form)
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])

    for k, v := range r.Form {
        fmt.Println("key", k)
        fmt.Println("val", strings.Join(v, ""))
    }

    fmt.Fprintf(w, "hello Go-web")
}

func main() {
    http.HandleFunc("/", sayHelloName)
    // log.Println("Serve listen at http://localhost:8900/")
    err := http.ListenAndServe(":8900", nil)

    if err != nil {
        log.Fatal("Listen & Serve Error", err)
    }
}

访问http://localhost:9090/?url_long=111&url_long=222

实际输出
map [url_long:[111 222]]
路径/
方案
[111 222]
密钥url_long
val 111222
地图[]
路径/favicon.ico
方案
[]
我不明白为什么这里有一个favicon.ico。
任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的浏览器实际上请求了/favicon.ico。如果您从外壳程序运行curl请求,则不会看到两个HandleFunc请求。

curl http://localhost:9090/?url_long=111&url_long=222

如果您要处理/favicon.ico路径,可以执行以下操作:

func faviconPath(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "path/to/favicon.ico")
}

func main() {
  http.HandleFunc("/favicon.ico", faviconPath)
}