brave.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package websearch
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. )
  11. const (
  12. braveSearchEndpoint = "https://api.search.brave.com/res/v1/web/search"
  13. braveMaxCount = 20
  14. braveProviderName = "brave"
  15. )
  16. // braveSearchURL is pre-parsed at init time; url.Parse cannot fail on a constant literal.
  17. var braveSearchURL, _ = url.Parse(braveSearchEndpoint) //nolint:errcheck
  18. // BraveProvider implements web search via the Brave Search API.
  19. type BraveProvider struct {
  20. apiKey string
  21. httpClient *http.Client
  22. }
  23. // NewBraveProvider creates a Brave Search provider.
  24. // The caller is responsible for configuring the http.Client with proxy/timeouts.
  25. func NewBraveProvider(apiKey string, httpClient *http.Client) *BraveProvider {
  26. if httpClient == nil {
  27. httpClient = http.DefaultClient
  28. }
  29. return &BraveProvider{apiKey: apiKey, httpClient: httpClient}
  30. }
  31. func (b *BraveProvider) Name() string { return braveProviderName }
  32. func (b *BraveProvider) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) {
  33. count := req.MaxResults
  34. if count <= 0 {
  35. count = defaultMaxResults
  36. }
  37. if count > braveMaxCount {
  38. count = braveMaxCount
  39. }
  40. u := *braveSearchURL // copy the pre-parsed URL
  41. q := u.Query()
  42. q.Set("q", req.Query)
  43. q.Set("count", strconv.Itoa(count))
  44. u.RawQuery = q.Encode()
  45. httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
  46. if err != nil {
  47. return nil, fmt.Errorf("brave: build request: %w", err)
  48. }
  49. httpReq.Header.Set("X-Subscription-Token", b.apiKey)
  50. httpReq.Header.Set("Accept", "application/json")
  51. resp, err := b.httpClient.Do(httpReq)
  52. if err != nil {
  53. return nil, fmt.Errorf("brave: request failed: %w", err)
  54. }
  55. defer func() { _ = resp.Body.Close() }()
  56. body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize))
  57. if err != nil {
  58. return nil, fmt.Errorf("brave: read body: %w", err)
  59. }
  60. if resp.StatusCode != http.StatusOK {
  61. return nil, fmt.Errorf("brave: status %d: %s", resp.StatusCode, truncateBody(body))
  62. }
  63. var raw braveResponse
  64. if err := json.Unmarshal(body, &raw); err != nil {
  65. return nil, fmt.Errorf("brave: decode response: %w", err)
  66. }
  67. results := make([]SearchResult, 0, len(raw.Web.Results))
  68. for _, r := range raw.Web.Results {
  69. results = append(results, SearchResult{
  70. URL: r.URL,
  71. Title: r.Title,
  72. Snippet: r.Description,
  73. PageAge: r.Age,
  74. })
  75. }
  76. return &SearchResponse{Results: results, Query: req.Query}, nil
  77. }
  78. // braveResponse is the minimal structure of the Brave Search API response.
  79. type braveResponse struct {
  80. Web struct {
  81. Results []braveResult `json:"results"`
  82. } `json:"web"`
  83. }
  84. type braveResult struct {
  85. URL string `json:"url"`
  86. Title string `json:"title"`
  87. Description string `json:"description"`
  88. Age string `json:"age"`
  89. }