I'm learning Golang so please excuse what may seem to be a basic question. I have searched for a couple of hours for clues as to how I might achieve sending variable data in my JSON formatted API POST from my golang app, but not found a clue or solution yet. I know the answer will be my lack of syntax knowledge.
So the problem is with the 'lastcontact' field I'm trying to POST. I want to use my 'dt' variable that contains the current datetime.
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
"time"
)
func main() {
dt := time.Now()
url := "https://fakeapi.io/API/apiActions/update/"
method := "POST"
payload := strings.NewReader(`{
"name" : "Dumpty",
"saveconfig" : "true",
"lastcontact" : {dt}
}`)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("api-key", "gjhgjhgjhg")
req.Header.Add("api-secret", "jhgjhgjhg")
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
fmtpackage, or explicit string concatenation with+, or a struct/map value with json.Marshal.