英文:
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())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论