0

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))
}
1
  • 2
    Go doesn't support this kind of automatic string interpolation of variables. You need to either use the fmt package, or explicit string concatenation with +, or a struct/map value with json.Marshal. Commented Mar 28, 2021 at 15:21

1 Answer 1

1

You can use a struct to store your response type if you know the fields beforehand. If you don't, you could use a map[string]interface{} to store arbitrary data.

Then using json.Marshal to convert it to a correctly formatted JSON response.

type myStruct struct {
        Name        string    `json:"name"`
        SaveConfig  string    `json:"saveconfig"`
        LastContact time.Time `json:"lastcontact"`
    }

    dt := time.Now()

    myData := myStruct{
        Name:        "Dumpty",
        SaveConfig:  "true",
        LastContact: dt,
    }

    myBytes, err := json.Marshal(myData)
    // bytes.NewBuffer returns *bytes.Buffer
    // which implements the io.Reader interface
    // that you need for your http.NewRequest call
    payload := bytes.NewBuffer(myBytes)

Full playground example https://play.golang.org/p/Mc9UXT32Wi1

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for your answer. Absolutely perfect. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.