Menu Close

Go – HTTP StatusText Function in Go

In this article, we will explore the http StatusText function in Go net/http package in detail, along with examples.

Introduction:

In Go, the net/http package provides a comprehensive interface for working with HTTP requests and responses. When dealing with HTTP responses, one of the key components is the status code, which communicates the outcome of an HTTP request. To make it easier to work with status codes, Go provides the http.StatusText function, which returns a human-readable string representation of the status code.

In this article, we’ll delve into the http.StatusText function in Go, discuss its usage, and provide a detailed example to help you understand how to use status codes in your own Go applications.

Overview of the http.StatusText Function

Syntax:

func StatusText(code int) string

The function takes a single arguments:

  • code: An integer representing an HTTP status code.

The function returns a string containing the text associated with the given status code, or an empty string if the status code is not recognized.

Example

package main

import (
    "fmt"
    "net/http"
)

func customStatusHandler(w http.ResponseWriter, r *http.Request) {
    // Define a custom status code
    customStatusCode := 418

    // Retrieve the status text for the custom status code
    statusText := http.StatusText(customStatusCode)

    // Set the status code and status text in the response
    w.WriteHeader(customStatusCode)
    fmt.Fprintf(w, "Status code: %d\nStatus text: %s", customStatusCode, statusText)
}

func main() {
    // Register the customStatusHandler function for the "/custom-status" route
    http.HandleFunc("/custom-status", customStatusHandler)

    // Start the web server
    fmt.Println("Starting server on :8080...")
    http.ListenAndServe(":8080", nil)
}

To test the application, run the program and visit http://localhost:8080/custom-status in your web browser. The server will respond with an HTTP response containing the custom status code “418” and the corresponding status text “I’m a teapot”.

Conclusion

The http.StatusText function in Go is a useful tool for working with HTTP status codes, allowing you to easily map status codes to their respective human-readable text descriptions. This can be especially helpful when debugging and logging HTTP responses. The example provided in this article demonstrates the basics of using the http.StatusText function in a Go web application, but remember that it can be used in any context where you need to work with HTTP status codes.

To check more Go related articles. Pls click given below link:

https://techieindoor.com/category/leetcode/

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *