duanping2005 2018-11-24 04:03
浏览 310
已采纳

无法成功实现http.Handler

I'm trying to get the following code to compile. I cannot successfully implement my own template handler struct an it results in the following error upon build.

Error:

./main.go:28:46: cannot use templateHandler literal (type *templateHandler) as type http.Handler in argument to http.Handle: *templateHandler does not implement http.Handler (missing ServeHTTP method)

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)
    }
}
  • 写回答

1条回答 默认 最新

  • dongyi2083 2018-11-24 04:35
    关注

    Interface has the following representation.

    type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
    }
    

    You're misspelled with the name. ServerHTTP/ServeHTTP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog