我正在尝试使用net / http将json文件发布到ElasticSearch.通常在Curl我会做以下事情: curl -XPOST localhost:9200/prod/aws -d @aws.json 在golang我用过一个例子,但它没有用.我可以看到它发布但必须设置错
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)
如果你想从文件中读取json然后使用.
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))
这应该工作
