refactor api package comments

* use encoding/json for comment parsing

* refactor by moving loop code to an UnmarshalJSON

* use a preallocated array and indices to maintain order while using
  goroutines again, this was removed a while ago

* use new struct in comment.hbs and contextComment.hbs

* rewriteUrl partial to reduce rimgo-specific code in api

* move RenderError into pages package to avoid import cycle between render and utils
This commit is contained in:
orangix
2026-01-25 05:08:10 +01:00
parent c208a55f40
commit 02be603dcc
15 changed files with 234 additions and 137 deletions

View File

@@ -1,6 +1,7 @@
package api
import (
"encoding/json"
"io"
"net/http"
"strings"
@@ -154,7 +155,7 @@ func (client *Client) FetchUserFavorites(username string, sort string, page stri
func (client *Client) FetchUserComments(username string) ([]Comment, error) {
cacheData, found := client.Cache.Get(username + "-usercomments")
if found {
return cacheData.([]Comment), nil
return cacheData.(commentArray), nil
}
req, err := http.NewRequest("GET", "https://api.imgur.com/comment/v1/comments", nil)
@@ -176,23 +177,19 @@ func (client *Client) FetchUserComments(username string) ([]Comment, error) {
return []Comment{}, err
}
body, err := io.ReadAll(res.Body)
data, err := io.ReadAll(res.Body)
if err != nil {
return []Comment{}, err
}
data := gjson.Parse(string(body))
var parsed commentApiResponse
err = json.Unmarshal(data, &parsed)
if err != nil {
return []Comment{}, err
}
comments := make([]Comment, 0)
data.Get("data").ForEach(
func(key, value gjson.Result) bool {
comments = append(comments, parseComment(value))
return true
},
)
client.Cache.Set(username+"-usercomments", comments, cache.DefaultExpiration)
return comments, nil
client.Cache.Set(username+"-usercomments", parsed.Data, cache.DefaultExpiration)
return parsed.Data, nil
}
func parseSubmission(value gjson.Result) Submission {