Reputation: 265
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)
Upvotes: 4
Views: 12568
Reputation: 156434
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.
Upvotes: 3
Reputation: 955
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
Upvotes: 8