TutorialEdge

How to print payload of Post request

I’m new to Go and trying to write a test REST API

I’m sending POST how I can read and print payload of Post request to make sure that it sends key: value correctly

Hey Contorax, welcome to the community!

You can craft the request using the http.NewRequest function which returns a http request. You can then print this out once you have set all the values and headers and then execute the request using a http client like this:

package main

  import (
    "fmt"
    "bytes"
    "encoding/json"
    "net/http"
  )

  func main() {

    client := http.Client{}

    body, err := json.Marshal(map[string]string{
      "name": "Elliot",
    })

    if err != nil {
      fmt.Println(err)
    }

    request, err := http.NewRequest("POST", "https://example.org", bytes.NewBuffer(body))
    if err != nil {
      fmt.Println(err)
    }

    fmt.Printf("%+v\n", request)

    resp, err := client.Do(request)
    if err != nil {
      fmt.Println(err)
    }
    
    fmt.Println(resp)
  }

The official docs for the Request struct can be found here: https://golang.org/pkg/net/http/#Request

Let me know if this helps!

1 Like