create a http server and read the request body in go

Here's an example of how to create an HTTP server and read the request body in Go:

main.go
package main

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

func main() {
    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // Read the request body
    requestBody, err := ioutil.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Error reading request body", http.StatusBadRequest)
        return
    }

    // Print the request body
    fmt.Fprintf(w, "Hello, %s", requestBody)
}
517 chars
26 lines

In this example, we create an HTTP server on port 8080 by calling http.ListenAndServe. We then define an HTTP handler function helloHandler to handle requests to the /hello path.

In the helloHandler function, we read the request body using ioutil.ReadAll(r.Body), which reads the entire request body into a byte slice. We then print the request body by calling fmt.Fprintf(w, "Hello, %s", requestBody) and passing the response writer (w) and the request body (requestBody) as arguments.

related categories

gistlibby LogSnag