【问题标题】:multiple response.WriteHeader calls in really simple example?多个 response.WriteHeader 在非常简单的示例中调用?
【发布时间】:2015-03-14 09:27:34
【问题描述】:

我有一个最基本的 net/http 程序,用来学习 Go 中的命名空间:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(r.URL)
        go HandleIndex(w, r)
    })

    fmt.Println("Starting Server...")
    log.Fatal(http.ListenAndServe(":5678", nil))
}

func HandleIndex(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(200)
    w.Write([]byte("Hello, World!"))
}

当我在 Chrome 中运行程序并连接到 localhost:5678 时,我在控制台中得到了这个:

Starting Server...
/
2015/01/15 13:41:29 http: multiple response.WriteHeader calls
/favicon.ico
2015/01/15 13:41:29 http: multiple response.WriteHeader calls

但我不明白这怎么可能。我打印 URL,启动一个新的 goroutine,编写一次标头,并给它一个静态的 Hello, World! 正文,似乎正在发生两件事之一。要么是幕后的东西正在编写另一个标头,要么以某种方式 HandleIndex 为同一个请求调用了两次。我该怎么做才能停止编写多个标题?

编辑:这似乎与go HandleIndex(w, r) 行有关,因为如果我删除go 并使其成为函数调用而不是goroutine,我不会遇到任何问题并且浏览器会获取它的数据.由于它是一个 goroutine,我得到了多个 WriteHeader 错误,并且浏览器没有显示“Hello World”。为什么要让这个 goroutine 破坏它?

【问题讨论】:

    标签: http go server


    【解决方案1】:

    看看你注册为传入请求处理程序的匿名函数:

    func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(r.URL)
        go HandleIndex(w, r)
    }
    

    它打印 URL(到标准输出)然后在一个新的 goroutine 中调用 HandleIndex() 并继续执行。

    如果你有一个处理函数,在第一次调用 Write 之前没有设置响应状态,Go 会自动将响应状态设置为 200(HTTP OK)。如果处理函数没有向响应写入任何内容(并且没有设置响应状态并正常完成),则也将其视为成功处理请求,并将返回响应状态 200。您的匿名函数没有设置它,它甚至没有向响应写入任何内容。所以 Go 会这样做:将响应状态设置为 200 HTTP OK。

    请注意,处理每个请求都在其自己的 goroutine 中运行。

    所以如果你在一个新的 goroutine 中调用 HandleIndex,你原来的匿名函数将继续:它会结束,所以响应头将被设置 - 同时(同时)你启动的新 goroutine 也将设置响应头 - 因此"multiple response.WriteHeader calls" 错误。

    如果你删除"go",你的HandleIndex函数将在你的处理函数返回之前在同一个goroutine中设置响应头,并且“net/http”会知道这一点并且不会尝试设置响应再次标头,因此您遇到的错误不会发生。

    【讨论】:

    • "请注意,处理每个请求都在其自己的 gorouting 中运行。"我希望它能做到这一点,但如果这是真的,我从来没有见过任何说法。
    • @CoreyOgburn 引用 http.Serve() 的文档:"Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each."
    【解决方案2】:

    您已经收到了解决您问题的正确答案,我将提供一些关于一般情况的信息(此类错误经常出现)。

    documentation 中,您看到WriteHeader 发送了一个http 状态代码,并且您不能发送超过1 个状态代码。如果你Write 什么都相当于发送 200 个状态码然后写东西。

    因此,如果您多次明确使用w.WriteHeader 或在w.WriteHeader 之前使用w.Write,则会显示您看到的消息。

    【讨论】:

      【解决方案3】:

      来自文档:

      // WriteHeader sends an HTTP response header with status code. 
      // If WriteHeader is not called explicitly, the first call to Write  
      // will trigger an implicit WriteHeader(http.StatusOK).
      

      您的情况是您正在从处理程序启动go HandleIndex。 第一个处理程序完成。标准 WriteHeader 写入 ResponseWriter。然后启动 goroutine HandleIndex,它也尝试写一个 header 和 write。

      只需从 HandleIndex 中删除 go 即可。

      【讨论】:

        【解决方案4】:

        根本原因是您多次调用 WriteHeader。来自源代码

        func (w *response) WriteHeader(code int) {
            if w.conn.hijacked() {
                w.conn.server.logf("http: response.WriteHeader on hijacked connection")
                return
            }
            if w.wroteHeader {
                w.conn.server.logf("http: multiple response.WriteHeader calls")
                return
            }
            w.wroteHeader = true
            w.status = code
        
            if w.calledHeader && w.cw.header == nil {
                w.cw.header = w.handlerHeader.clone()
            }
        
            if cl := w.handlerHeader.get("Content-Length"); cl != "" {
                v, err := strconv.ParseInt(cl, 10, 64)
                if err == nil && v >= 0 {
                    w.contentLength = v
                } else {
                    w.conn.server.logf("http: invalid Content-Length of %q", cl)
                    w.handlerHeader.Del("Content-Length")
                }
            }
        }
        

        所以当你写一次时,变量 writeHeader 为真,然后你再次写 header,它不会生效并给出警告“http: multiple respnse.WriteHeader calls”。 实际上函数Write也调用了WriteHeader,所以把函数WriteHeader放在函数Write之后也会导致该错误,而后面的WriteHeader不起作用。

        从你的情况来看,go handleindex在另一个线程中运行,原来的已经返回,如果你什么都不做,它会调用WriteHeader设置200。运行handleindex时,它会调用另一个WriteHeader,此时writeHeader为true,那么输出消息“http: multiple response.WriteHeader calls”。

        【讨论】:

          【解决方案5】:

          是的,使用HandleIndex(w, r) 而不是go HandleIndex(w, r) 可以解决您的问题,我想您已经弄清楚了。

          原因很简单,当同时处理多个请求时,http server会启动多个goroutine,你的handler函数会在每个goroutine中单独调用,不会阻塞其他的。 您不需要在处理程序中启动自己的 goroutine,除非您实际上需要它,但这将是另一个话题。

          【讨论】:

            【解决方案6】:

            因为现代浏览器会发送一个额外的 /favicon.ico 请求,该请求也在您的 / 请求处理程序中处理。

            例如,如果您使用 curl ping 服务器,您将看到只发送一个请求:

             curl localhost:5678
            

            为了确保您可以在 http.HandleFunc 中添加 EndPoint

            http.HandleFunc("/Home", func(w http.ResponseWriter, r *http.Request) 
            

            【讨论】:

              猜你喜欢
              • 2016-06-06
              • 1970-01-01
              • 1970-01-01
              • 2017-05-31
              • 2016-03-26
              • 2022-01-15
              • 1970-01-01
              • 1970-01-01
              • 2011-10-26
              相关资源
              最近更新 更多