登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-13 16:42:29 187浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《为什么在 Go 中使用自定义 http.Handler 时要传递指针?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

在下面的代码片段中调用 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)
    }
}

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

cannot use (templateHandler literal) (value of type templateHandler) 
as http.Handler value in argument to http.Handle: 
missing method ServeHTTP

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


解决方案


http.Handle() 需要一个实现 http.Handler 的值(任何值),这意味着它必须具有 servehttp() 方法。

您对 templatehandler.servehttp() 方法使用了指针接收器,这意味着只有指向 templatehandler 的指针值才有此方法,而不是非指针 templatehandler 类型的指针值。

Spec: Method sets:

类型可能有与其关联的方法集interface type的方法集就是它的接口。任何其他类型 t 的方法集由使用接收器类型 t 声明的所有 methods 组成。对应的pointer type *t的方法集是用接收者*tt声明的所有方法集(即还包含t的方法集)。

非指针类型仅具有非指针接收器的方法。指针类型具有带有指针和非指针接收器的方法。

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>