create a http server and read the request body as text in go

You can create an HTTP server and read the request body as text in Go using the net/http package. Here's an example:

main.go
package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Read request body
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer r.Body.Close()

        // Print request body as text
        fmt.Fprintf(w, "Request Body: %s", string(body))
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}
544 chars
26 lines

In this example, we define an HTTP request handler using http.HandleFunc that reads the request body using ioutil.ReadAll(r.Body), checks for errors, and then prints the body as text using fmt.Fprintf(w, ...).

To start the server, we use http.ListenAndServe(":8080", nil). This starts an HTTP server on localhost:8080 with the default handler, which is the handler we defined using http.HandleFunc.

Note that we defer r.Body.Close() to ensure that the request body is always closed after we're done reading it. This is important to prevent resource leaks.

gistlibby LogSnag