user1678808
user1678808

Reputation:

How to interpolate a byte slice?

I'm attempting to build a JSON payload for a POST request:

var payload = []byte(`{"foo":"bar", "hello":"world"}`)

However, I would like the values to be interpolated from an existing string. I've tried to use %s, but this is obviously not syntactically correct:

var payload = []byte(`{"foo":%s, "hello":%s}`, val1, val2)

Feels like I'm going about this the entirely wrong way. Any suggestions would be appreciated. Thanks.

Upvotes: 0

Views: 1227

Answers (1)

creack
creack

Reputation: 121832

To use %s, you need a formatting function.

var payload = []byte(fmt.Sprintf(`{"foo":%q, "hello":%q}`, val1, val2))

(%q is like %s but adds quotes for you)

Upvotes: 5

Related Questions