为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕森卡 2023-06-26 16:38:18
当调用http.Handle()下面的代码片段时,我使用自己的templateHandler类型来实现该http.Handler接口。package mainimport (    "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究竟为什么会发生这种情况?在这种情况下使用指针有什么区别?指针去方法界面
查看完整描述

1 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

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{})

}


查看完整回答
反对 回复 2023-06-26
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信