Не удается успешно реализовать http.Handler - PullRequest
0 голосов
/ 24 ноября 2018

Я пытаюсь получить следующий код для компиляции.Я не могу успешно реализовать свой собственный шаблонный обработчик struct a, это приводит к следующей ошибке при сборке.

Ошибка:

. / Main.go: 28: 46: невозможно использовать литерал templateHandler (тип *templateHandler) как тип http.Handler в аргументе для http.Handle: * 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)
    }
}

1 Ответ

0 голосов
/ 24 ноября 2018

Интерфейс имеет следующее представление.

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

Вы неправильно написали имя.ServerHTTP / ServeHTTP.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...