douxian8883 2017-01-06 21:17
浏览 20
已采纳

如何在Go中的字节片中使用变量

Probably a big noob question here, so please bear with me.

To send an HTTP POST request in Go with some body, I can do this:

var jsonStr = []byte(`{"someVar":"someValue"}`)
req, err := http.NewRequest("POST", APIURL, bytes.NewBuffer(jsonStr))

However, it seems that I can't use a variable instead of "someValue", like this:

someValue := "SomeValue"
var jsonStr = []byte(`{"someVar":someValue}`)

Can someone point me in the right direction?

  • 写回答

2条回答 默认 最新

  • dougou8458 2017-01-06 21:23
    关注

    That is because it is a string literal. I suggest trying to serialize your type using encoding/json.

    type MyPostBody struct {
        SomeVar string `json:"someVar"`
    }
    
    pb := &MyPostBody{SomeVar: "someValue"}
    jsonStr, err := json.Marshal(pb)
    if err != nil {
        log.Fatalf("could not marshal JSON: %s", err)
    }
    
    req, err := http.NewRequest("POST", APIURL, bytes.NewBuffer(jsonStr))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿