http ResponseWriter重复回答golang

huangapple go评论69阅读模式
英文:

http ResponseWriter duplicate answer golang

问题

以下是代码的中文翻译:

func main() {

  http.HandleFunc("/", foo)

  http.ListenAndServe(":3000", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {

  s := "name"

  fp := path.Join("templates", "index.html")

  tmpl, err := template.ParseFiles(fp)
  if err != nil {
    panic(err)
  }

  if err := tmpl.Execute(w, s); err != nil {
    panic(err)
  }

  fmt.Println("成功的操作!!")
}

这段代码会显示两次"成功的操作!!",但当我添加/home (http.HandleFunc("/home", foo))时,它只显示一次。我想知道为什么会显示两次"成功的操作!!"。提前谢谢你。

英文:
func main() {

  http.HandleFunc("/", foo)

  http.ListenAndServe(":3000", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {

  s:= "name"

  fp := path.Join("templates", "index.html")

  tmpl, err := template.ParseFiles(fp)
  if err != nil {
    panic(err)
  }

  if  err := tmpl.Execute(w, s); err != nil {
    panic(err)
  }

  fmt.Println("successfull Operation!!")

}

This code displays 2 "successfull Operation!!" but when I add /home (http.HandleFunc("/home", foo)), it doesn't. I want to know why it displays "successfull Operation!!" twice. Thank you in advance.

答案1

得分: 5

因为现代浏览器会发送一个额外的请求/favicon.ico,这个请求也会在你的/请求处理程序中处理。

如果你使用curl对你的服务器进行ping测试,你会看到只发送了一个请求:

 curl localhost:3000
英文:

Because modern browsers send an extra request for /favicon.ico which is also handled in your / request handler.

If you ping your server with curl for example, you'll see only one request being sent:

 curl localhost:3000

huangapple
  • 本文由 发表于 2015年4月30日 23:59:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/29972502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定