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

huangapple go评论77阅读模式
英文:

How to use a variable in byte slice in Go

问题

可能是一个很菜鸟的问题,请耐心等待。

在Go语言中发送带有请求体的HTTP POST请求,可以这样做:

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

然而,似乎我不能使用变量代替"someValue",像这样:

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

有人可以指点我正确的方向吗?

英文:

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?

答案1

得分: 7

将字符串格式化或转换为特定格式的代码示例:

someValue := "SomeValue"
var jsonStr = []byte(fmt.Sprintf(`{"someVar":"%v"}`, someValue))

这段代码将字符串格式化为 JSON 格式的字符串。其中,someValue 是要格式化的字符串变量,通过 fmt.Sprintf 函数将其插入到 JSON 字符串中。最终,jsonStr 变量将包含格式化后的 JSON 字符串。

英文:

or format the string

someValue := "SomeValue"
var jsonStr = []byte(fmt.Sprintf(`{"someVar":"%v"}`, someValue))

答案2

得分: 6

这是因为它是一个字符串字面量。我建议尝试使用encoding/json来序列化你的类型。

type MyPostBody struct {
    SomeVar string `json:"someVar"`
}

pb := &MyPostBody{SomeVar: "someValue"}
jsonStr, err := json.Marshal(pb)
if err != nil {
    log.Fatalf("无法序列化JSON:%s", err)
}

req, err := http.NewRequest("POST", APIURL, bytes.NewBuffer(jsonStr))
英文:

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))

huangapple
  • 本文由 发表于 2017年1月7日 05:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/41514498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定