duane-stubbs
2/15/2018 - 3:10 PM

Post JSON to URL

Post Json to URL

    
    url := "http://theURL.com"
    
    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{
      Timeout: time.Second * 10,
    }
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
    
    // Credit: https://stackoverflow.com/questions/24455147/how-do-i-send-a-json-string-in-a-post-request-in-go