2018-11-24 04:03 阅读 157


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.


./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 (

// 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 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.

    点赞 1 评论 复制链接分享