Standard library / net/http

http.Error()

Writes a plain-text error response with the supplied status. Return from the handler afterward; this function does not stop execution. Expected stdout: '400 bad input\n'.

Formal Syntax & Structure

go syntaxgo
func Error(w ResponseWriter, error string, code int)

Parameters & Attributes

NameTypeDescription
wResponseWriterDestination writer.
errorstringPlain-text response error message.
codeintHTTP status code.

Working Example

Example Snippetgo
package main
import (  "fmt"  "net/http"  "net/http/httptest"  "strings")
func main() {  w := httptest.NewRecorder()  http.Error(w, "bad input", 400)  fmt.Println(w.Code, strings.TrimSpace(w.Body.String()))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference