英文:
http.HandleFunc invokes root handler 3 times per request
问题
package main
import (
"fmt"
"io"
"html/template"
"net/http"
"log"
)
type pageFunc func() (string, interface{})
func thread() (string, interface{}) {
return "thread", nil
}
func main() {
t := template.New("main")
t.ParseGlob("templates/*.xhtml")
respond := func(f pageFunc) http.HandlerFunc {
fmt.Println("respond 1")
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("respond 2")
name, data := f()
t.ExecuteTemplate(w, name, data)
}
}
http.HandleFunc("/", respond(thread))
err := http.ListenAndServe(":7842", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
英文:
package main
import (
"fmt"
"io"
"html/template"
"net/http"
"log"
)
type pageFunc func() (string, interface{})
func thread() (string, interface{}) {
return "thread", nil
}
func main() {
t := template.New("main")
t.ParseGlob("templates/*.xhtml")
respond := func(f pageFunc) http.HandlerFunc {
fmt.Println("respond 1")
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("respond 2")
name, data := f()
t.ExecuteTemplate(w, name, data)
}
}
http.HandleFunc("/", respond(thread))
err := http.ListenAndServe(":7842", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Starting the program above and sending a single request to http://localhost:7842/
causes the console to output:
respond 1
respond 2
respond 2
respond 2
It only appears to invoke the handler a single time if I comment out:
name, data := f()
t.ExecuteTemplate(w, name, data)
In that case I just get:
respond 1
respond 2
This is completely beyond my comprehension. How would calling t.ExecuteTemplate cause the function it's invoked from to run more than once? Even more bizarre (to me, at least) is that if I change the path slightly, like so,
http.HandleFunc("/a", respond(thread))
... it once again only fires the handler function once, even with the templating function uncommented. What is happening?
The template in question, if it interests anyone:
{{ define "thread" }}<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test thread page</title>
<link rel="stylesheet" type="text/css" href="/static/board.css" />
<script type="text/javascript" src="/static/general.js"></script>
</head>
<body>
<h1>hello, world.</h1>
</body>
</html>
{{ end }}
答案1
得分: 3
如果“单个请求”是由浏览器发出的,那么实际上可能不止一个请求。例如,某些浏览器可能会请求网站的图标。如果您想要确保只有一个请求,我建议您编写一个简单的工具来实现这个目的。
英文:
If the "single request" is made by a browser then it may actually be more than one request. Eg. some browsers may ask for a site favicon. If you want a guaranteed single request then I would recommend to write a simple tool for that purpose.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论