Use fmt.Fprintf

ID

go.use_fprintf

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Go

Tags

best-practice, code-style

Description

Reports w.Write([]byte(fmt.Sprintf(format, args…​))). Formatting into a string, converting it to a byte slice, and writing the slice can be done in one step with fmt.Fprintf(w, format, args…​).

Rationale

fmt.Fprintf writes formatted output straight to an io.Writer. The manual chain builds an intermediate string, allocates a fresh []byte to copy it, and only then writes — two allocations and a copy that Fprintf avoids. The single call is also shorter and makes the destination of the output obvious.

// Bad
w.Write([]byte(fmt.Sprintf("hello %s", name)))

// Good
fmt.Fprintf(w, "hello %s", name)

Remediation

Replace w.Write([]byte(fmt.Sprintf(format, args…​))) with fmt.Fprintf(w, format, args…​).