【问题标题】:Cannot successfully implement http.Handler无法成功实现 http.Handler
【发布时间】: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


    【解决方案1】:

    接口有以下表示。

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

    你的名字拼错了。服务器HTTP/ServeHTTP。

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2021-08-22
      • 2015-12-19
      相关资源
      最近更新 更多