how to set status code golang http

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprintf(w, "Custom 404 Not Found Page")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Explanation:

  1. Import the necessary packages: fmt and net/http.

  2. Define a function named handler that takes in two parameters, w (http.ResponseWriter) and r (http.Request).

  3. Inside the handler function:

    • Use w.WriteHeader(http.StatusNotFound) to set the status code of the HTTP response to 404 Not Found.
    • Use fmt.Fprintf(w, "Custom 404 Not Found Page") to write a custom message "Custom 404 Not Found Page" as the response body.
  4. In the main function:

    • Use http.HandleFunc("/", handler) to set up a request handler for the root path ("/").
    • Use http.ListenAndServe(":8080", nil) to start an HTTP server on port 8080. The server uses the default router and handler, which is specified by passing nil as the second parameter to ListenAndServe.