Golang net/http.Error() function example

package net/http

Golang net/http.Error() function usage example

 package main

 import (
 "net/http"
 )

 func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
 html := "Hello"
 html = html + " World"

 w.Write([]byte(html))
 }

 func SayError(w http.ResponseWriter, r *http.Request) {
 http.Error(w, "Say Error!", 500)
 }

 func main() {
 mux := http.NewServeMux()
 mux.HandleFunc("/", SayHelloWorld)
 mux.HandleFunc("/error", SayError)

 http.ListenAndServe(":8080", mux)
 }

Sample output :

From browser :

Point to URL [your server]:8080/error

Say Error!

From terminal :

curl -I [your server]:8080/error

HTTP/1.1 500 Internal Server Error

Content-Type: text/plain; charset=utf-8

Date: Mon, 25 May 2015 06:29:48 GMT

Content-Length: 11

See Also : https://www.socketloop.com/tutorials/golang-how-to-return-http-status-code

Reference :

http://golang.org/pkg/net/http/#Error

Advertisement