Skip to content

httptest allows headers to be written after http.ResponseWriter.WriteHeader is called #14914

@andrewhare

Description

@andrewhare
  1. What version of Go are you using (go version)?
go version go1.6 darwin/amd64
  1. What operating system and processor architecture are you using (go env)?
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/drew/go"
GORACE=""
GOROOT="/usr/local/opt/go/libexec"
GOTOOLDIR="/usr/local/opt/go/libexec/pkg/tool/darwin_amd64"
GO15VENDOREXPERIMENT="1"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"
  1. What did you do?
package main

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

const (
    header = "Content-Type"
    value  = "application/json"
    addr   = "localhost:8080"
)

func TestHandler(w http.ResponseWriter, req *http.Request) {
    w.Header().Set(header, value)
    w.WriteHeader(http.StatusOK)
}

func TestWrongOrderHandler(w http.ResponseWriter, req *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set(header, value)
}

func main() {
    http.HandleFunc("/test", TestHandler)
    http.HandleFunc("/testWrongOrder", TestWrongOrderHandler)
    go http.ListenAndServe(addr, nil)

    checkHeaderValue("/test")
    checkHeaderValue("/testWrongOrder")
}

func checkHeaderValue(path string) {
    req, _ := http.NewRequest("GET", path, nil)
    rec := httptest.NewRecorder()
    http.DefaultServeMux.ServeHTTP(rec, req)
    fmt.Println(path, "(httptest)", rec.HeaderMap[header][0])

    resp, _ := http.Get("http://" + addr + path)
    fmt.Println(path, "(http.Get)", resp.Header[header][0])
}
  1. What did you expect to see?
/test (httptest) application/json
/test (http.Get) application/json
/testWrongOrder (httptest) text/plain; charset=utf-8
/testWrongOrder (http.Get) text/plain; charset=utf-8
  1. What did you see instead?
/test (httptest) application/json
/test (http.Get) application/json
/testWrongOrder (httptest) application/json
/testWrongOrder (http.Get) text/plain; charset=utf-8

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions