在 Go 中使用自定义 http.Handler 时为什么要使用指针?

当调用http.Handle()下面的代码片段时,我使用自己的templateHandler类型来实现该http.Handler接口。


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)

    }

}

现在由于某种原因我必须传递一个指向http.Handle()using的指针&templateHandler{filename: "chat.html"}。如果没有,&我会收到以下错误:


cannot use (templateHandler literal) (value of type templateHandler) 

as http.Handler value in argument to http.Handle: 

missing method ServeHTTP

究竟为什么会发生这种情况?在这种情况下使用指针有什么区别?


指针去方法界面


慕森卡
浏览 95回答 1
1回答

炎炎设计

http.Handle()需要一个实现 的值(任何值)http.Handler,这意味着它必须有一个ServeHTTP()方法。您为该templateHandler.ServeHTTP()方法使用了指针接收器,这意味着只有指针值才有templateHandler此方法,而不是非指针templateHandler类型的指针值。规格: 方法集:类型可以具有与其关联的方法集。接口类型的方法集就是它的接口。任何其他类型的方法集由使用接收者类型声明的T所有方法T组成。对应指针类型 的方法集是用receiver或*T声明的所有方法的集合(即还包含 的方法集)。*TTT非指针类型仅具有带有非指针接收器的方法。指针类型具有带有指针和非指针接收器的方法。您的ServeHTTP()方法修改了接收者,因此它必须是一个指针。但如果其他处理程序不需要,则ServeHTTP()可以使用非指针接收器创建该方法,在这种情况下,您可以使用非指针值作为http.Handler,如下例所示:type myhandler struct{}func (m myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}func main() {    // non-pointer struct value implements http.Handler:    http.Handle("/", myhandler{})}
打开App,查看更多内容
随时随地看视频慕课网APP