Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 结构接收器到外部函数_Go - Fatal编程技术网

Go 结构接收器到外部函数

Go 结构接收器到外部函数,go,Go,我真的不懂这个代码 我想我理解接收方是如何工作的,但当/foo被请求时,为什么该结构成为从未调用过的接收方到服务的ttp呢?如果http就是这样工作的,那么这是接收器的典型使用方式吗 main go import "net/http" type fooHandler struct { Message sstring } func (f *fooHandler) ServerHTTP(w http.ResponseWriter, r *http.Request)

我真的不懂这个代码

我想我理解接收方是如何工作的,但当/foo被请求时,为什么该结构成为从未调用过的接收方到服务的ttp呢?如果http就是这样工作的,那么这是接收器的典型使用方式吗

main go

import "net/http"

type fooHandler struct {
    Message sstring
}

func (f *fooHandler) ServerHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(f.Message))
}

func main() {
    http.Handle("/foo", &fooHandler{Message: "Hello world"})
}

第一:它应该是
ServeHTTP
,而不是
ServerHTTP


使用
ServeHTTP
方法,
foodhandler
是一个实现
http.Handler
接口的结构。因此,您可以将
&foodhandler
传递到
http.Handle
,当加载该URL时,将调用
foodhandler
ServeHTTP
方法。

这可能有助于感谢链接非常好@abhijitgupta,我觉得我现在理解得多了。。非常感谢。