0

I have a body response that I can only get Byte responses. This bytes encode a csv-like response. Something like:

element_a,element_b,element_c
cooper,claus,active
carlos,saldanha,inactive
robert,jesus,active

Lets say then that I have the struct that looks like this:

type ESResponse struct {
ElementA string `csv:"element_a"`
ElementB string `csv:"element_b"`
ElementC string `csv:"element_c"`
}

I would like to unmarshal the byte response so then I'm able to access its elements.

What I've been doing is the following:

var actualResult ESResponse

body := util.GetResponseBody() // this is where the byte response comes from. 
in := string(body[:]) // here I transform it to a string but I trully think this is not the best way. 
err = gocsv.Unmarshal(in, &actualResult)

I've been using this library here: https://pkg.go.dev/github.com/gocarina/gocsv#section-readme but I'm unable to understand the error I get which is:

cannot use in (variable of type string) as io.Reader value in argument to gocsv.Unmarshal: string does not implement io.Reader (missing method Read)
mkopriva
  • 35,176
  • 4
  • 57
  • 71
hcp
  • 319
  • 2
  • 16
  • `gocsv.Unmarshal(bytes.NewReader(body), &actualResult)` But note that your `actualResult` is a single struct instance, that won't be able to hold all the csv's records, just one. You should probably pass a slice of structs instead of just a single struct. Look through the repo's documentation, very likely there's an example in the readme or somewhere in the test files if there are any. – mkopriva Dec 21 '22 at 20:09

1 Answers1

2

It means, that in argument must implement interface io.Reader, but you argument's type is string, which doesn't. So if you want to deserialize value from string, you can do this:

    body := `
element_a,element_b,element_c
cooper,claus,active
carlos,saldanha,inactive
robert,jesus,active`
    var actualResult []ESResponse
    in := strings.NewReader(body)
    err := gocsv.Unmarshal(in, &actualResult)

or gocsv.Unmarshal(bytes.NewReader([]byte(body)), &actualResult) to deserialize from bytes array

Artem Astashov
  • 646
  • 6
  • 10