From 08be497fae653fed9d6c12f14e4ec215cfba7237 Mon Sep 17 00:00:00 2001 From: rjp Date: Thu, 25 May 2023 08:36:53 +0100 Subject: [PATCH] Revert to simple `io.Writer` with client-resetting After going through several other solutions, there's no clean way to use an `io.Writer` but also be able to call `Reset()` between writes. Filehandles can't `Reset()` and buffers can't `Seek()`. But then if you supplied `os.Stderr`, you'd be expecting appending and a `Seek()` would be nonsense. My own preference would be to make `JSONWriter` a strict `*bytes.Buffer` which lets the library handle the resetting and the client do any outputting if required - I can't see much value in ever supplying a non-`bytes.Buffer` as `JSONWriter`. --- mastodon.go | 8 +------- status_test.go | 6 ++++-- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/mastodon.go b/mastodon.go index 309bac2..385efcb 100644 --- a/mastodon.go +++ b/mastodon.go @@ -24,17 +24,12 @@ type Config struct { AccessToken string } -type WriteResetter interface { - io.Writer - Reset() -} - // Client is a API client for mastodon. type Client struct { http.Client Config *Config UserAgent string - JSONWriter WriteResetter + JSONWriter io.Writer } func (c *Client) doAPI(ctx context.Context, method string, uri string, params interface{}, res interface{}, pg *Pagination) error { @@ -133,7 +128,6 @@ func (c *Client) doAPI(ctx context.Context, method string, uri string, params in } if c.JSONWriter != nil { - c.JSONWriter.Reset() return json.NewDecoder(io.TeeReader(resp.Body, c.JSONWriter)).Decode(&res) } else { return json.NewDecoder(resp.Body).Decode(&res) diff --git a/status_test.go b/status_test.go index b3f5e8c..a54b931 100644 --- a/status_test.go +++ b/status_test.go @@ -1,6 +1,7 @@ package mastodon import ( + "bytes" "context" "fmt" "io/ioutil" @@ -52,7 +53,8 @@ func TestGetFavouritesSavedJSON(t *testing.T) { AccessToken: "zoo", }) - client.SaveJSON = true + var buf bytes.Buffer + client.JSONWriter = &buf favs, err := client.GetFavourites(context.Background(), nil) if err != nil { @@ -70,7 +72,7 @@ func TestGetFavouritesSavedJSON(t *testing.T) { // We get a trailing `\n` from the API which we need to trim // off before we compare it with our literal above. - theirJSON := strings.TrimSpace(string(client.LastJSON)) + theirJSON := strings.TrimSpace(string(buf.Bytes())) if theirJSON != ourJSON { t.Fatalf("want %q but %q", ourJSON, theirJSON)