dongshi7350 2017-07-16 22:10
浏览 110
已采纳

防止golang http.NewRequest向括号内添加括号

This must be fairly simple, but I can't work out why, when making an HTTP request with go, the body of the request gets wrapped in an additional set of braces:

package main

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

func main() {
    jsonStr := []byte(`{"some":"test","json":"data"}`)
    req, _ := http.NewRequest("POST", "http://test.com", bytes.NewBuffer(jsonStr))
    fmt.Print(req.Body)
}

This results in:

{{"some":"test","json":"data"}}

In my actual code I'm using the json.Marshal and a struct to generate the byte buffer, but getting the same result. The result is the API rejecting the request (as expected).

How do I prevent the extra braces being added?

  • 写回答

1条回答 默认 最新

  • duanlan7903 2017-07-17 04:01
    关注

    The printed representation of the body is not the same as the contents of the reader. The http.NewRequest function does not add braces to POST body.

    Here's what's going on:

    The body is a ioutil.nopCloser with the Reader field set to the *bytes.Buffer.

    The fmt.Print function prints the ioutil.nopCloser struct as { + fields + }. This is the extra set of braces in the printed output. The fmt.Print function prints the Reader field by calling the *bytes.Buffer.String method. The String method returns the contents as a string.

    The body is sent by reading it, not by printing it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?