【发布时间】:2019-11-01 07:41:56
【问题描述】:
在下面的代码 sn-p 中调用 http.Handle() 时,我使用了自己的 templateHandler 类型,它实现了 http.Handler 接口。
package main
import (
"html/template"
"log"
"net/http"
"path/filepath"
"sync"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
t.templ.Execute(w, nil)
}
func main() {
http.Handle("/", &templateHandler{filename: "chat.html"})
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
现在出于某种原因,我必须使用 &templateHandler{filename: "chat.html"} 传递指向 http.Handle() 的指针。如果没有&,我会收到以下错误:
cannot use (templateHandler literal) (value of type templateHandler)
as http.Handler value in argument to http.Handle:
missing method ServeHTTP
为什么会发生这种情况?在这种情况下使用指针有什么不同?
【问题讨论】:
标签: pointers go methods interface