繁体   English   中英

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

[英]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}`)

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

那是因为它是字符串文字。 我建议尝试使用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))

或格式化字符串

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

暂无
暂无

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

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