http.Post数据二进制,在golang中等效的curl

时间:2015-04-09 04:41:31

标签: go elasticsearch

我尝试使用net / http将json文件发布到ElasticSearch。通常在Curl中我会做以下事情:

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

在golang中,我使用过一个例子,但它没有用。我可以看到它发布但必须设置错误的东西。我已经测试了我正在使用的JSON文件,它很不错。

转到代码:

  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)

2 个答案:

答案 0 :(得分:6)

如果你想从文件中读取json,请使用。

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

在http post请求中发布json的简单方法。

    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))

这应该有效

答案 1 :(得分:1)

请注意,您可以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

这可能比首先将文件内容读入内存更好,特别是如果文件非常大。