jsongo

Get JSON representation of request body as a string


I would like to take an arbitrary http.Request and get the body as a json string. I know this involves the json package, but it seems json.Decode needs a specific struct passed in by reference. How can I decode an arbitrary request body (and then stringify the result)?

func RequestBodyJsonString(r *http.Request) string {

}

Solution

  • Use io.ReadAll to get data in byte slice then type conversion to string to get json string

    bytedata, err := io.ReadAll(r.Body)
    reqBodyString := string(bytedata)
    

    An example in go playground here