multiple response.WriteHeader calls in really simple example?

后端 未结 6 511
慢半拍i
慢半拍i 2020-12-10 10:43

I have the most basic net/http program that I\'m using to learn the namespace in Go:

package main

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

func          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 11:05

    the root cause is that you called WriteHeader more than once. from the source codes

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

    so when you wrote once, the variable wroteHeader would be true, then you wrote header again, it wouldn't be effective and gave a warning "http: multiple respnse.WriteHeader calls". actually the function Write also calls WriteHeader, so putting the function WriteHeader after the function Write also causes that error, and the later WriteHeader doesn't work.

    from your case, go handleindex runs in another thread and the original already returns, if you do nothing, it will call WriteHeader to set 200. when running handleindex, it calls another WriteHeader, at that time wroteHeader is true, then the message "http: multiple response.WriteHeader calls" is output.

提交回复
热议问题