自定义 Go 的 http 库中的现有处理程序

发布于 2024-09-12 06:29:08 字数 384 浏览 1 评论 0原文

按照 http 库中的说明定义以下内容:

func Handle(pattern string, handler Handler)
type Handler interface { ServeHTTP(*Conn, *Request) }

如何通过给现有处理程序(例如,websocket.Draft75Handler)提供附加参数来改进它(并告诉它如何处理该参数)?

我正在尝试创建一个处理程序,其中包含通道的一端。它将使用该通道与程序的其他部分进行对话。如何将该通道放入处理程序函数中?

如果这是一个愚蠢的问题,我深表歉意。我是 Go 新手,决定通过阅读教程来学习,然后直接进入代码。感谢您的帮助!

With the following being defined as is noted in the http library:

func Handle(pattern string, handler Handler)
type Handler interface { ServeHTTP(*Conn, *Request) }

How can I improve upon an existing handler (say, websocket.Draft75Handler for instance) by giving it an additional argument (and tell it what to do with the argument)?

I'm trying to create a handler that contains within it one end of a channel. It will use that channel to talk to some other part of the program. How can I get that channel into the the handler function?

Apologies if this is a silly question. I'm new at go and decided to learn by reading the tutorial and then jumping right into code. Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞琼窗梦回ˉ 2024-09-19 06:29:08

如果类型是一个函数,例如 websocket.Draft75Handler,您可以将其包装在闭包中:

func MyHandler(arg interface{}) websocket.Draft75Handler {
    return func(c *http.ConnConn) {
        // handle request
    }
}

func main() {
    http.Handle("/echo", MyHandler("argument"))
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        panic("ListenAndServe: " + err.String())
    }
}

If the type is a function, like websocket.Draft75Handler, you could wrap it in a closure:

func MyHandler(arg interface{}) websocket.Draft75Handler {
    return func(c *http.ConnConn) {
        // handle request
    }
}

func main() {
    http.Handle("/echo", MyHandler("argument"))
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        panic("ListenAndServe: " + err.String())
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文