cl

啊,好吧,我要做一个纯粹的猜测,并提出你被太多的概念混合在一个小代码块绊倒了。

http.Handle()func some_name(list_of_args) bodycl

我们可以“展开”该代码,使其看起来更容易理解:

cl, err := native.Connect(...)

handler := func(w http.ResponseWriter, r *http.Request) {
  h, err := createCall(cl)
  ...
}

http.Handle("/", http.HandlerFunc(handler))

现在看起来更合理了吗?

handlercl

你能做些什么?

我们可以尝试将其改写为更简单的内容:

cl, err := native.Connect(...)

func handler(w http.ResponseWriter, r *http.Request) {
  h, err := createCall(cl) // Oops, this won't compile
  ...
}

http.Handle("/", http.HandlerFunc(handler))

但是这段代码不会编译,因为常规函数不能引用包含函数定义的词法范围中的变量(我们不要离题了,为什么会这样)。

那么,你能对此做些什么?

handlenet/http.HandlerFunc

那么,让我们这样做:

type myHander struct {
  cl native.Client // I have no idea which type native.Connect returns...
}

func (*mh myHandler) handle(w http.ResponseWriter, r *http.Request) {
  h, err := createCall(mh.cl)
  ...
}

我们现在可以将其传递给设置内容的代码:

mh := myHandler{
  cl: cl,
}
http.Handle("/", http.HandlerFunc(mh.handle))

更好的方法

net/http.HandlerFunc
HandlerFunc
net/http.HandlerServeHTTP(http.ResponseWriter, *http.Request)myHandler.handle

所以我们的类型可以变成

type myHander struct {
  cl native.Client // I have no idea which type native.Connect returns...
}

func (*mh myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  h, err := createCall(mh.cl)
  ...
}

然后我们就可以

mh := myHandler{
  cl: cl,
}
http.Handle("/", &mh)