【发布时间】:2018-11-24 04:03:35
【问题描述】:
我正在尝试编译以下代码。我无法成功实现自己的模板处理程序结构,它会在构建时导致以下错误。
错误:
./main.go:28:46: 不能在 http.Handle 的参数中使用 templateHandler 文字(类型 *templateHandler)作为类型 http.Handler: *templateHandler 没有实现http.Handler(缺少ServeHTTP方法)
package main
import (
"html/template"
"log"
"net/http"
"path/filepath"
"sync"
)
// templ represents a single template
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServerHTTP(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"})
// Start Web Server
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
【问题讨论】:
标签: http templates go webserver