Golang net/http.NotFound() function example

package net/http

Golang net/http.NotFound() function usage example

 package main

 import (
  "net/http"
 )

 func returnCode200(w http.ResponseWriter, r *http.Request) {
  // see http://golang.org/pkg/net/http/#pkg-constants
  w.WriteHeader(http.StatusOK)
  w.Write([]byte("☄ HTTP status code returned!"))
 }

 func returnCode500(w http.ResponseWriter, r *http.Request) {
  // see http://golang.org/pkg/net/http/#pkg-constants
  w.WriteHeader(http.StatusInternalServerError)
  w.Write([]byte("☄ HTTP status code returned!"))
 }

 func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/", returnCode200)
  mux.HandleFunc("/fivehundred", returnCode500)
  mux.HandleFunc("/notfound", http.NotFound) <---- here !

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

Sample output :

URL : http://:8080/notfound

404 page not found

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

Reference :

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

Advertisement