Home > Software engineering >  send array to golang server using curl
send array to golang server using curl

Time:05-06

I have a simple HTTP server running. I am trying to send a list of values to this server using curl.

curl -X POST -d "["student1", "student2"]" http://localhost:8080/

How can I read the body as a string slice? I tried b, _ := io.ReadAll(r.Body) but it reads the array as one item rather than an array.

CodePudding user response:

You can use json decoder to decode the values in slice of string

var arr []string
err := json.NewDecoder(req.Body).Decode(&arr)
if err != nil {
    fmt.Fprintf(w,fmt.Sprintf("Error:% v",err))
    return
}
fmt.Println(arr)

CodePudding user response:

Try with this :P

curl -X POST -d '["student1", "student2"]' http://localhost:8080

The quotes were breaking the payload parsing.

This also works:

curl -X POST -d "[\"student1\", \"student2\"]" http://localhost:8080

Your go server is probably reciving a payload that looks like this [student1, student2] instead of looking like this ["student1", "student2"]

After you have your well formed json string array being sent, you can parse it like this:

var body []string
e := json.NewDecoder(r.Body).Decode(&body)
fmt.Println(e, body[0]) // nil "student1"
  • Related