sync of changes

This commit is contained in:
2024-11-09 19:50:14 -05:00
parent cc7b03c614
commit a83d5f9822
9 changed files with 491 additions and 95 deletions

View File

@@ -1,18 +1,30 @@
package search
import (
"answer/pkg/cache"
"context"
googlesearch "github.com/rocketlaunchr/google-search"
"sort"
)
type Google struct {
Cache cache.Cache
}
var _ Search = Google{}
func (Google) Search(ctx context.Context, search string) ([]Result, error) {
res, err := googlesearch.Search(ctx, search, googlesearch.SearchOptions{
func (g Google) Search(ctx context.Context, search string) ([]Result, error) {
var res []Result
key := "google:" + search
err := g.Cache.GetJSON(key, &res)
if err == nil {
return res, nil
}
results, err := googlesearch.Search(ctx, search, googlesearch.SearchOptions{
CountryCode: "",
LanguageCode: "",
Limit: 0,
@@ -27,18 +39,20 @@ func (Google) Search(ctx context.Context, search string) ([]Result, error) {
return nil, err
}
var results []Result
// just in case, sort the res by rank, as the api does not mention it is sorted
sort.Slice(res, func(i, j int) bool {
return res[i].Rank < res[j].Rank
return results[i].Rank < results[j].Rank
})
for _, r := range res {
results = append(results, Result{
for _, r := range results {
res = append(res, Result{
Title: r.Title,
URL: r.URL,
Description: r.Description,
})
}
_ = g.Cache.SetJSON(key, res)
return res, nil
}