Skip to content

Commit

Permalink
Gate the JSON saving behind a client flag
Browse files Browse the repository at this point in the history
This way the library will behave as it used to for anyone who doesn't
explicitly set `client.SaveJSON` to be `true`.  No surprises = good.
  • Loading branch information
rjp authored and mattn committed Oct 24, 2024
1 parent 0f299f7 commit 2d49fbb
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions mastodon.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Client struct {
http.Client
Config *Config
UserAgent string
SaveJSON bool
LastJSON []byte
}

Expand Down Expand Up @@ -127,17 +128,22 @@ func (c *Client) doAPI(ctx context.Context, method string, uri string, params in
}
}

// If we want to store the JSON received, we absolutely have to
// read all of it. But we restrict ourselves to a max of 100M.
safer := &io.LimitedReader{resp.Body, 100 * 1_048_576}
c.LastJSON, err = io.ReadAll(safer)
if c.SaveJSON {
// We want to store the JSON received -> we absolutely have to
// read all of it. But we restrict ourselves to a max of 100M.
safer := &io.LimitedReader{resp.Body, 100 * 1_048_576}
c.LastJSON, err = io.ReadAll(safer)

if err != nil || c.LastJSON == nil {
return err
}
if err != nil || c.LastJSON == nil {
return err
}

// ...which means we can't use `NewDecoder.Decode` any more.
return json.Unmarshal(c.LastJSON, &res)
// ...which means we can't use `NewDecoder.Decode` any more.
return json.Unmarshal(c.LastJSON, &res)
} else {
// We don't want the JSON, just do the previous streaming decode.
return json.NewDecoder(resp.Body).Decode(&res)
}
}

// NewClient returns a new mastodon API client.
Expand Down

0 comments on commit 2d49fbb

Please sign in to comment.