dongwen6743 2014-10-25 01:16
浏览 23
已采纳

前往:在一个函数中接受不同的套接字调用

I'm trying to get my web server to accept different socket calls in one function. My code looks like this:

Go:

func handler(w io.Writer, r *io.ReadCloser) {
    //do something
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":3000", nil)
}

I get the error:

cannot use handler (type func(io.Writer, *io.ReadCloser)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

How do I implement this?

  • 写回答

1条回答 默认 最新

  • dptn69182 2014-10-25 04:52
    关注

    As shown in the article "Writing Web Applications", the example for HandleFunc is:

    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)
    }
    

    You cannot replace a r *http.Request by an r *io.ReadCloser.

    You would need to delegate that call in a wrapper, as suggested in this thread:

    func wrappingHandler(w http.ResponseWriter, r *http.Request){
        handler(w, r.Body)
    }
    func main() {
        http.HandleFunc("/", wrappingHandler)
        http.ListenAndServe(":8080", nil)
    }
    

    Or simply modify your handler:

    func handler(w http.ResponseWriter, r *http.Request) {
        rb := r.Body
        //do something with rb instead of r
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗