Use HTTP Status Constants

ID

go.use_http_status_constants

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Go

Tags

best-practice, code-style

Description

Reports a magic HTTP status code written as a bare integer literal in a net/http call — for example w.WriteHeader(404) or http.Error(w, msg, 500) — instead of the named constant from net/http, such as http.StatusNotFound.

Two families of call site are inspected, each scoped to net/http so an unrelated same-named method or function is never matched:

  • w.WriteHeader(<status>) where the receiver w is an http.ResponseWriter;

  • the status argument of http.Error (3rd argument), http.Redirect (4th argument), http.StatusText (1st argument) and http.RedirectHandler (2nd argument).

Only an integer literal in the typical HTTP status range (100–599) is flagged.

Rationale

Numeric status codes are opaque at the call site and easy to mistype: a 200 where 204 was intended passes review unnoticed. The net/http constants are self-documenting and verified by the compiler, so a misspelled name fails to build rather than shipping a wrong response. Named constants (http.StatusOK) and variables are never reported.

// Bad
w.WriteHeader(404)
http.Error(w, "boom", 500)

// Good
w.WriteHeader(http.StatusNotFound)
http.Error(w, "boom", http.StatusInternalServerError)

Remediation

Replace the literal with the matching http.Status* constant.