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:
Import the necessary packages:
fmt
andnet/http
.Define a function named
handler
that takes in two parameters,w
(http.ResponseWriter) andr
(http.Request).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.
- Use
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 passingnil
as the second parameter toListenAndServe
.
- Use