简体   繁体   English

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

[英]Go: accept different socket calls in one function

I'm trying to get my web server to accept different socket calls in one function. 我正在尝试让我的Web服务器在一个函数中接受不同的套接字调用。 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? 我该如何实施?

As shown in the article " Writing Web Applications ", the example for HandleFunc is: 如文章“ 编写Web应用程序 ”所示,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)
}

You cannot replace a r *http.Request by an r *io.ReadCloser . 您不能用r *http.Request替换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
}

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

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