登录
首页 >  Golang >  Go问答

在 golang 中将对象从一个包传递到下一个包

来源:stackoverflow

时间:2024-04-16 18:39:35 227浏览 收藏

哈喽!今天心血来潮给大家带来了《在 golang 中将对象从一个包传递到下一个包》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

来自 github,https://github.com/cycoresystems/ari/blob/master/_examples/stasisstart/main.go

我正在查看下面的启动,对象被保存到 cl 中,然后用于创建handlefun..全部在同一个主体中..如果我想将其分解并将handlefunc 放入另一个包中,我如何将 cl 传递给是吗?

cl, err := native.connect(&native.options{
        application:  "test",
        username:     "asterisk",
        password:     "abc123",
        url:          "http://localhost:8088/ari",
        websocketurl: "ws://localhost:8088/ari/events",
    })

后来就这样过去了

http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // make call
        log.Info("Make sample call")
        h, err := createCall(cl)
        if err != nil {
            log.Error("Failed to create call", "error", err)
            w.WriteHeader(http.StatusBadGateway)
            w.Write([]byte("Failed to create call: " + err.Error()))
            return
        }

        w.WriteHeader(http.StatusOK)
        w.Write([]byte(h.ID()))
    }))

解决方案


cl 如何“传递给”处理函数

啊,好吧,我将做一个纯粹的猜测,并建议您被一小块代码中混合的太多概念所绊倒。

http.handle() 的第二个参数是所谓的“函数文字”——“现场”函数的定义,而不是“像 func some_name(list_of_args 那样”的正常方式定义它) ) 身体。 go 中的函数字面量是“闭包”,这意味着它们从可用的外部词法范围中“捕获”任何变量,它们的函数体通过名称引用这些变量。您的示例中的函数文字指的是 cl,因此它“关闭”该变量。

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

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

handler := func(w http.responsewriter, r *http.request) {
  h, err := createcall(cl)
  ...
}

http.handle("/", http.handlerfunc(handler))

现在看起来是不是更明智了?

无论分配给变量 handler 的是什么,都是一个以变量 cl 结束的函数值。

你能做些什么?

我们可以尝试将其重写得更简单:

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

但是这段代码不会编译,因为常规函数无法引用包含函数定义的词法作用域中的变量(我们不要离题)。

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

您不能只是将另一个参数添加到 handle 的参数列表中,因为它必须具有特定的签名,即 net/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))

更好的方法

但是如果我们使用 rtfm,我们可以做得更好(提示!): net/http.handlerfunc 上的文档说:

handlerfunc 类型是一个适配器,允许使用普通函数作为 http 处理程序。

因此,如果我们浏览文档来了解“http 处理程序”是什么,我们会得到 net/http.Handler,它是一个接口类型,并且任何具有方法 servehttp(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)

Further reading

您可以将处理程序代码提取到单独的工厂函数中:

func makehandler(cl *conn) http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        // make call
        log.info("make sample call")
        h, err := createcall(cl)
        if err != nil {
            log.error("failed to create call", "error", err)
            w.writeheader(http.statusbadgateway)
            w.write([]byte("failed to create call: " + err.error()))
            return
        }

        w.writeheader(http.statusok)
        w.write([]byte(h.id()))
    })  
}

然后在你原来的范围内使用它。

http.Handle("/", otherpkg.MakeHandler(cl))

理论要掌握,实操不能落!以上关于《在 golang 中将对象从一个包传递到下一个包》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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