package search import ( "answer/pkg/cache" "context" googlesearch "github.com/rocketlaunchr/google-search" "sort" ) type Google struct { Cache cache.Cache } var _ Search = Google{} 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, Start: 0, UserAgent: "", OverLimit: false, ProxyAddr: "", FollowNextPage: false, }) if err != nil { return nil, err } // 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 results[i].Rank < results[j].Rank }) 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 }