From 78d8d7fc430a59c004c4408ad498ea5eae2d7b53 Mon Sep 17 00:00:00 2001 From: rjp Date: Tue, 23 May 2023 08:27:55 +0100 Subject: [PATCH] Keep the API JSON around (briefly) For my archival purposes, I like to keep the raw API JSON around as it often contains things not picked up by the various objects. e.g. getting a status from my Akkoma instance contains a whole `pleroma` extension block that's not reflected in `mastodon.Status`. Maybe this should be gated by an option when creating the `Client` since it's probably only relevant to 1% of library users. --- mastodon.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/mastodon.go b/mastodon.go index c704e10..ff58f28 100644 --- a/mastodon.go +++ b/mastodon.go @@ -29,6 +29,7 @@ type Client struct { http.Client Config *Config UserAgent string + LastJSON []byte } func (c *Client) doAPI(ctx context.Context, method string, uri string, params interface{}, res interface{}, pg *Pagination) error { @@ -125,7 +126,18 @@ func (c *Client) doAPI(ctx context.Context, method string, uri string, params in *pg = *pg2 } } - return json.NewDecoder(resp.Body).Decode(&res) + + // 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 err != nil || c.LastJSON == nil { + return err + } + + // ...which means we can't use `NewDecoder.Decode` any more. + return json.Unmarshal(c.LastJSON, &res) } // NewClient returns a new mastodon API client.