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

无法成功实现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.

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

报告相同问题?