Request and responses.

Request and responses.

You can use the io to get the request body from an HTTPrequest in io.ReadAll() function to read ther.Body object representing the incoming request body. Here is an example of how you can do this:

package main

import (

func handler(w http.ResponseWriter, r *http.Request) {
    // Read the request body
    body, err := io.ReadAll(r.Body)

    if err != nil {
        // Handle the error by sending an HTTP status code 
        // and message back to the client.
        http.Error(w, "Error reading request body", 

    // Ensure that request body is closed.
    defer func(Body io.ReadCloser) {
        err := Body.Close()
        if err != nil {
            fmt.Print("Error while closing the body", 

    // Use the request body here
    // For example, echoing the request body back to the client
    _, err = w.Write(body)
    if err != nil {
        fmt.Println("Error while writing the body", err.Error())
    } // Note: In a real application, check the error from Write

func main() {
    // Register the handler function for the root path
    http.HandleFunc("/", handler)

    // Start the HTTP server on port 8080
    // ListenAndServe always returns a non-nil error.
    // After Shutdown or Close, the returned error is 
    // ErrServerClosed.
    if err := http.ListenAndServe(":8080", nil); err != nil {
        if errors.Is(err, http.ErrServerClosed) {
            fmt.Println("Server closed.")

        // Unexpected error. Log and exit.

That was your nugget 😄.

Until the next one… May the source be with you 🦄.

Section Contents