Skip to content

Commit

Permalink
feat: cache errored request
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-ding committed Aug 13, 2024
1 parent 3291434 commit b487c81
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
2 changes: 1 addition & 1 deletion pkg/torznab/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ import (
"time"
)

var cc = cache.NewCache[string, Response](time.Minute * 30)
var cc = cache.NewCache[string, *Response](time.Minute * 30)
33 changes: 21 additions & 12 deletions pkg/torznab/torznab.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,26 +135,35 @@ func Search(indexer *db.TorznabInfo, keyWord string) ([]Result, error) {

cacheRes, ok := cc.Get(key)
if !ok {
resp, err := http.DefaultClient.Do(req)
res, err := doRequest(req)
if err != nil {
return nil, errors.Wrap(err, "do http")
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "read http body")
}
var res Response
err = xml.Unmarshal(data, &res)
if err != nil {
return nil, errors.Wrapf(err, "xml unmarshal data: %v", string(data))
cc.Set(key, &Response{})
return nil, errors.Wrap(err, "do http request")
}
cacheRes = res
cc.Set(key, cacheRes)
}
return cacheRes.ToResults(indexer), nil
}

func doRequest(req *http.Request) (*Response, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "do http")
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "read http body")
}
var res Response
err = xml.Unmarshal(data, &res)
if err != nil {
return nil, errors.Wrapf(err, "xml unmarshal data: %v", string(data))
}
return &res, nil
}

type Result struct {
Name string `json:"name"`
Link string `json:"link"`
Expand Down

0 comments on commit b487c81

Please sign in to comment.