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

Tim*_*Ski 3 go elasticsearch

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

curl -XPOST localhost:9200/prod/aws -d @aws.json
Run Code Online (Sandbox Code Playgroud)

在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)
Run Code Online (Sandbox Code Playgroud)

Aka*_*nde 6

如果你想从文件中读取json然后使用.

jsonStr,err := ioutil.ReadFile("filename.json")
if(err!=nil){
    panic(err)
}
Run Code Online (Sandbox Code Playgroud)

在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))
Run Code Online (Sandbox Code Playgroud)

这应该工作