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

huangapple go评论89阅读模式
英文:

Customizing an existing handler in Go's http library

问题

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!

答案1

得分: 2

如果类型是一个函数,比如websocket.Draft75Handler,你可以将它包装在一个闭包中:

func MyHandler(arg interface{}) websocket.Draft75Handler {
    return func(c *http.ConnConn) {
        // 处理请求
    }
}

func main() {
    http.Handle("/echo", MyHandler("参数"))
    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())
    }
}

huangapple
  • 本文由 发表于 2010年8月2日 17:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/3386585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定