1

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.

0

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.