Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.Post data-binary, curl equivalent in golang

I'm trying to use net/http to post a json file to ElasticSearch. Normally in Curl I would do the following:

curl -XPOST localhost:9200/prod/aws -d @aws.json

In golang I've used an example but it has not worked. I can see it posting but something must be set incorrectly. I've tested the JSON file I am using and it's good to go.

Go code:

  target_url := "http://localhost:9200/prod/aws"
  body_buf := bytes.NewBufferString("")
  body_writer := multipart.NewWriter(body_buf)
  jsonfile := "aws.json"
  file_writer, err := body_writer.CreateFormFile("upfile", jsonfile)
  if err != nil {
    fmt.Println("error writing to buffer")
    return
  }
  fh, err := os.Open(jsonfile)
  if err != nil {
    fmt.Println("error opening file")
    return
  }
  io.Copy(file_writer, fh)
  body_writer.Close()
  http.Post(target_url, "application/json", body_buf)
like image 722
Tim Ski Avatar asked Oct 18 '25 16:10

Tim Ski


2 Answers

If you want to read json from file then use .

jsonStr,err := ioutil.ReadFile("filename.json")
if(err!=nil){
    panic(err)
}

Simple way to post json in http post request.

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("Content-Type", "application/json")

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

    fmt.Println("response Status:", resp.Status)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))

This should work

like image 111
Akash Shinde Avatar answered Oct 20 '25 05:10

Akash Shinde


Note that you can Post with an io.Reader as the body:

file, err := os.Open("./aws.json")
resp, err := http.Post(targetUrl, "application/json", file)
// TODO: handle errors

This might work better than reading the file contents into memory first, especially if the file is very large.

like image 38
maerics Avatar answered Oct 20 '25 05:10

maerics



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!