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

huangapple go评论88阅读模式
英文:

Go: accept different socket calls in one function

问题

我正在尝试让我的Web服务器在一个函数中接受不同的套接字调用。我的代码如下:

Go语言:

func handler(w io.Writer, r *io.ReadCloser) {
    //做一些操作
}

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

我得到了以下错误:

无法将handler(类型为func(io.Writer,*io.ReadCloser))用作类型为func(http.ResponseWriter,*http.Request)的参数传递给http.HandleFunc

我该如何实现这个?

英文:

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

得分: 1

如文章“编写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)
}

你不能用r *io.ReadCloser替换r *http.Request

你需要在一个包装器中委托该调用,如此线程中建议的:

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
    // 使用 rb 而不是 r 进行操作
}
英文:

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
}

huangapple
  • 本文由 发表于 2014年10月25日 09:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/26558426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定