Reputation: 15048
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?
Upvotes: 0
Views: 2605
Reputation: 178
or format the string
someValue := "SomeValue"
var jsonStr = []byte(fmt.Sprintf(`{"someVar":"%v"}`, someValue))
Upvotes: 7
Reputation: 33380
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))
Upvotes: 6