简体   繁体   English

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

[英]How to use a variable in byte slice in 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: 要在Go中发送带有正文的HTTP POST请求,我可以这样做:

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 := "SomeValue"
var jsonStr = []byte(`{"someVar":someValue}`)

Can someone point me in the right direction? 有人可以指出我正确的方向吗?

That is because it is a string literal. 那是因为它是字符串文字。 I suggest trying to serialize your type using encoding/json . 我建议尝试使用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))

or format the string 或格式化字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM