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.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向