我试图让我的Web服务器在一个函数中接受不同的套接字调用。我的代码如下所示:
转到:
func handler(w io.Writer, r *io.ReadCloser) {
//do something
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
我收到错误:
cannot use handler (type func(io.Writer, *io.ReadCloser)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc
我该如何实现?
答案 0 :(得分:1)
如文章" Writing Web Applications"所示,HandleFunc的示例是:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
您无法用r *http.Request
替换r *io.ReadCloser
。
您需要按照建议in this thread:
在包装器中委派该调用func wrappingHandler(w http.ResponseWriter, r *http.Request){
handler(w, r.Body)
}
func main() {
http.HandleFunc("/", wrappingHandler)
http.ListenAndServe(":8080", nil)
}
或者只是修改你的处理程序:
func handler(w http.ResponseWriter, r *http.Request) {
rb := r.Body
//do something with rb instead of r
}