When calling http.Handle()
in the code snippet below, I'm using my own templateHandler
type which implements the http.Handler
interface.
package main
import (
"html/template"
"log"
"net/http"
"path/filepath"
"sync"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
func (t *templateHandler) ServeHTTP(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"})
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Now for some reason I have to pass a pointer to http.Handle()
using &templateHandler{filename: "chat.html"}
. Without the &
I get the following error:
cannot use (templateHandler literal) (value of type templateHandler)
as http.Handler value in argument to http.Handle:
missing method ServeHTTP
Why exactly is this happening? What difference does using a pointer make in this case?