Skip to content

cmd/vet: check for http.ResponseWriter WriteHeader calls after body has been written #27668

Description

@adamdecaf

What version of Go are you using (go version)?

$ go version
go version go1.11 linux/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

Details
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/adam/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/adam/code"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build369596792=/tmp/go-build -gno-record-gcc-switches"

What did you do?

Consider the following code:

package main

import (
        "encoding/json"
        "fmt"
        "net/http"
)

func main() {
        http.HandleFunc("/ping", func (w http.ResponseWriter, r *http.Request) {
                type response struct {
                        Error error `json:"error"`
                }
                if err := json.NewEncoder(w).Encode(response{nil}); err != nil {
                        fmt.Println(err)
                }
                w.Header().Set("Content-Type", "application/json; charset=utf-8")
        })

        go http.ListenAndServe(":6060", nil)

        resp, err := http.Get("http://localhost:6060")
        if err != nil {
                panic(err)
        }
        fmt.Println(resp.Header.Get("Content-Type"))
}

This code outputs:

$ go run /tmp/vet/main.go
text/plain; charset=utf-8

Comments

It would be nice for vet to be aware of this common mistake and be able to alert the developer to an easy fix. The documentation for http.ResponseWriter describes all the details, but that's often missed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    AnalysisIssues related to static analysis (vet, x/tools/go/analysis)FeatureRequestIssues asking for a new feature that does not need a proposal.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions