Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement io.Reader #52

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Implement io.Reader #52

wants to merge 2 commits into from

Conversation

xoen
Copy link

@xoen xoen commented Apr 22, 2016

simplejson.Json implements the io.Reader interface:

type Reader interface {
  Read(p []byte) (n int, err error)
}
Why?

By implementing this standard interface simplejson would play nice with the standard library and all the 3rd party packages that work with an io.Reader.

For example, it would allow to POST the JSON directly rather than being forced to Encode() and use bytes.NewReader():

// Currently
import ("bytes")
payloadBytes, _ := payloadJson.Encode()
req, _ := http.NewRequest("POST", "http://www.example.com", bytes.NewReader(payloadBytes))

// With io.Reader
req, _ := http.NewRequest("POST", "http://www.example.com", payloadJson)
Implementation

When starting to read the Json it encodes the data and save the bytes in the Reader struct.
This struct also keeps the index of the bytes read so far.
At every read the bytes are copied to the buffer argument and the index is increased.

(See bytes.Read() implementation)

The reader is reseted when Json.data changes

I'm far from a Go expert, so happy to receive feedback.

Tests

The test builds a first *simplejson, then a second one using NewFromReader(), this test would fail if *simplejson doesn't implement io.Reader.

Also, to test that the second JSON is equivalent with the original one (so Read() returns the correct bytes) I encode and compare them.

xoen added 2 commits April 22, 2016 00:16
As the reader pointer contains the bytes for the JSON, whne it changes these
would not be valid anymore.

NOTE: If the JSON changes between 2 Read() calls the result would still be
      incorrect as the 2nd read would returns bytes from the new JSON.
      Not sure how this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant