简体   繁体   English

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

[英]Customizing an existing handler in Go's http library

With the following being defined as is noted in the http library: 按照http库中的说明定义以下内容:

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)? 我如何通过给它一个附加参数(并告诉它如何处理该参数)来改进现有处理程序(例如, websocket.Draft75Handler )?

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! 谢谢你的帮助!

If the type is a function, like websocket.Draft75Handler , you could wrap it in a closure: 如果类型是函数,例如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())
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM