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

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

Go: accept different socket calls in one function

问题

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

Go语言:

  1. func handler(w io.Writer, r *io.ReadCloser) {
  2. //做一些操作
  3. }
  4. func main() {
  5. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  6. handler(w, &r.Body)
  7. })
  8. http.ListenAndServe(":3000", nil)
  9. }

我得到了以下错误:

  1. 无法将handler(类型为funcio.Writer,*io.ReadCloser))用作类型为funchttp.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:

  1. func handler(w io.Writer, r *io.ReadCloser) {
  2. //do something
  3. }
  4. func main() {
  5. http.HandleFunc("/", handler)
  6. http.ListenAndServe(":3000", nil)
  7. }

I get the error:

  1. 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的示例代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func handler(w http.ResponseWriter, r *http.Request) {
  7. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  8. }
  9. func main() {
  10. http.HandleFunc("/", handler)
  11. http.ListenAndServe(":8080", nil)
  12. }

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

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

  1. func wrappingHandler(w http.ResponseWriter, r *http.Request){
  2. handler(w, r.Body)
  3. }
  4. func main() {
  5. http.HandleFunc("/", wrappingHandler)
  6. http.ListenAndServe(":8080", nil)
  7. }

或者简单地修改你的处理函数:

  1. func handler(w http.ResponseWriter, r *http.Request) {
  2. rb := r.Body
  3. // 使用 rb 而不是 r 进行操作
  4. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func handler(w http.ResponseWriter, r *http.Request) {
  7. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  8. }
  9. func main() {
  10. http.HandleFunc("/", handler)
  11. http.ListenAndServe(":8080", nil)
  12. }

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:

  1. func wrappingHandler(w http.ResponseWriter, r *http.Request){
  2. handler(w, r.Body)
  3. }
  4. func main() {
  5. http.HandleFunc("/", wrappingHandler)
  6. http.ListenAndServe(":8080", nil)
  7. }

Or simply modify your handler:

  1. func handler(w http.ResponseWriter, r *http.Request) {
  2. rb := r.Body
  3. //do something with rb instead of r
  4. }

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:

确定