bravesearch

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 12 Imported by: 0

README

Go Reference Go Report Card

A Go client library for the Brave Search API - This library provides a simple and idiomatic Go interface to interact with Brave's search services.

Features

  • Simple, idiomatic Go API
  • Support for Brave's Web Search API
  • Configurable via functional options pattern
  • Clear error handling
  • Fully typed request and response structures

Installation

go get github.com/claywarren/go-brave-search

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	bravesearch "github.com/claywarren/go-brave-search"
)

func main() {
	// Create a new client with your API key
	client, err := bravesearch.NewClient("your-api-key-here")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create a context
	ctx := context.Background()

	// Perform a web search
	results, err := client.WebSearch(ctx, "brave search", nil)
	if err != nil {
		log.Fatalf("Search failed: %v", err)
	}

	// Print the results
	fmt.Printf("Search results for 'brave search':\n")
	for i, result := range results.Web.Results {
		fmt.Printf("%d. %s\n", i+1, result.Title)
		fmt.Printf("   URL: %s\n", result.URL)
		fmt.Printf("   Description: %s\n\n", result.Description)
	}
}

Advanced Usage

With Options
package main

import (
	"context"
	"fmt"
	"log"

	bravesearch "github.com/claywarren/go-brave-search"
)

func main() {
	// Create a client with options
	client, err := bravesearch.NewClient(
		"your-api-key-here",
		bravesearch.WithTimeout(30), // seconds
		bravesearch.WithDefaultCountry("JP"),
		bravesearch.WithDefaultSearchLanguage("ja"),
		bravesearch.WithDefaultUILanguage("ja-JP"),
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create a context
	ctx := context.Background()

	// Create search params
	params := &bravesearch.WebSearchParams{
		Count:      10,
		Offset:     0,
		SafeSearch: bravesearch.SafeSearchModerate,
		Freshness:  bravesearch.FreshnessWeek,
	}

	// Perform a web search with params
	results, err := client.WebSearch(ctx, "golang programming", params)
	if err != nil {
		log.Fatalf("Search failed: %v", err)
	}

	// Print the results
	fmt.Printf("Found %d results\n", len(results.Web.Results))
	for i, result := range results.Web.Results {
		fmt.Printf("%d. %s\n", i+1, result.Title)
	}
}

API Reference

For detailed API documentation, see the Go Reference.

Client

Client is the main entry point for using the library:

// Create a new client
client, err := bravesearch.NewClient("api-key")

// Create a client with options
client, err := bravesearch.NewClient(
    "api-key",
    bravesearch.WithTimeout(30),
    bravesearch.WithUserAgent("MyApp/1.0"),
)
// Simple search
results, err := client.WebSearch(ctx, "query", nil)

// Search with parameters
params := &bravesearch.WebSearchParams{
    Count:       20,
    Offset:      0,
    Country:     "US",
    SearchLang:  "en",
    UILang:      "en-US",
    SafeSearch:  bravesearch.SafeSearchModerate,
    Freshness:   bravesearch.FreshnessMonth,
    Spellcheck:  true,
}
results, err := client.WebSearch(ctx, "query", params)

Error Handling

The library provides detailed error information. Errors are wrapped with descriptive messages and can be unwrapped for more details.

if err != nil {
    if bravesearch.IsRateLimitError(err) {
        // Handle rate limit error
    } else if bravesearch.IsAuthError(err) {
        // Handle authentication error
    } else {
        // Handle other errors
    }
}

Configuration

The library supports several configuration options through functional options pattern:

client, err := bravesearch.NewClient(
    "api-key",
    bravesearch.WithTimeout(30),                   // Request timeout in seconds
    bravesearch.WithRetries(3),                    // Number of retries on transient errors
    bravesearch.WithUserAgent("MyApp/1.0"),        // Custom User-Agent
    bravesearch.WithDefaultCountry("JP"),          // Default country for searches
    bravesearch.WithDefaultSearchLanguage("ja"),   // Default search language
    bravesearch.WithDefaultUILanguage("ja-JP"),    // Default UI language
)

Development Status

This library is currently in active development. While it's functional and tested, we're continuously improving it. Feedback and contributions are welcome!

License

MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Acknowledgments

  • This library is not officially associated with or endorsed by Brave Software, Inc.
  • Thanks to Brave for providing an excellent search API

Documentation

Overview

Package bravesearch provides a Go client for the Brave Search API.

This package allows Go applications to interact with Brave's search services, including the Web Search API. It provides a simple, idiomatic interface with support for configuration via functional options.

Example usage:

client, err := bravesearch.NewClient("your-api-key")
if err != nil {
	log.Fatal(err)
}

results, err := client.WebSearch(context.Background(), "brave search", nil)
if err != nil {
	log.Fatal(err)
}

for _, result := range results.Web.Results {
	fmt.Printf("%s - %s\n", result.Title, result.URL)
}

Index

Constants

View Source
const (
	// BaseURL is the base URL for Brave Search API
	BaseURL = "https://api.search.brave.com/res/v1"

	// WebSearchEndpoint is the endpoint for web search
	WebSearchEndpoint = "/web/search"
)

API Endpoints

View Source
const (
	MaxWebSearchCount  = 20
	MaxWebSearchOffset = 9
)

Web Search API limits.

View Source
const (
	SafeSearchOff      = "off"
	SafeSearchModerate = "moderate"
	SafeSearchStrict   = "strict"
)

SafeSearch options

View Source
const (
	FreshnessDay   = "pd" // Past day
	FreshnessWeek  = "pw" // Past week
	FreshnessMonth = "pm" // Past month
	FreshnessYear  = "py" // Past year
)

Freshness options

View Source
const (
	DefaultCount      = 20
	DefaultOffset     = 0
	DefaultSafeSearch = SafeSearchModerate
	DefaultCountry    = "US"
	DefaultSearchLang = "en"
	DefaultUILang     = "en-US"
	DefaultTimeout    = 30 // seconds
	DefaultMaxRetries = 2
	DefaultUserAgent  = "go-brave-search/0.3.2"
	DefaultTextDecor  = true
	DefaultSpellCheck = true
)

Default values

View Source
const (
	HeaderAccept            = "Accept"
	HeaderAcceptEncoding    = "Accept-Encoding"
	HeaderUserAgent         = "User-Agent"
	HeaderSubscriptionToken = "X-Subscription-Token"
	HeaderCacheControl      = "Cache-Control"
	HeaderLocLatitude       = "X-Loc-Lat"
	HeaderLocLongitude      = "X-Loc-Long"
	HeaderLocTimezone       = "X-Loc-Timezone"
	HeaderLocCity           = "X-Loc-City"
	HeaderLocState          = "X-Loc-State"
	HeaderLocStateName      = "X-Loc-State-Name"
	HeaderLocCountry        = "X-Loc-Country"
	HeaderLocPostalCode     = "X-Loc-Postal-Code"
)

HTTP Headers

View Source
const (
	HeaderRateLimitLimit     = "X-RateLimit-Limit"
	HeaderRateLimitPolicy    = "X-RateLimit-Policy"
	HeaderRateLimitRemaining = "X-RateLimit-Remaining"
	HeaderRateLimitReset     = "X-RateLimit-Reset"
)

Response Headers

View Source
const (
	MIMETypeJSON = "application/json"
	MIMETypeGzip = "gzip"
)

MIME types

View Source
const (
	ResultFilterDiscussions = "discussions"
	ResultFilterFaq         = "faq"
	ResultFilterInfobox     = "infobox"
	ResultFilterNews        = "news"
	ResultFilterQuery       = "query"
	ResultFilterSummarizer  = "summarizer"
	ResultFilterVideos      = "videos"
	ResultFilterWeb         = "web"
	ResultFilterLocations   = "locations"
)

Result filters

View Source
const (
	UnitMetric   = "metric"
	UnitImperial = "imperial"
)

Units

View Source
const UserAgentPrefix = "go-brave-search"

UserAgentPrefix is the prefix for the user agent string

View Source
const Version = "0.3.2"

Version is the current version of the client library

Variables

View Source
var (
	// ErrMissingAPIKey is returned when the API key is missing
	ErrMissingAPIKey = errors.New("missing API key")

	// ErrInvalidAPIKey is returned when the API key is invalid
	ErrInvalidAPIKey = errors.New("invalid API key")

	// ErrRateLimit is returned when the API rate limit is exceeded
	ErrRateLimit = errors.New("rate limit exceeded")

	// ErrUnauthorized is returned when the API returns a 401 Unauthorized
	ErrUnauthorized = errors.New("unauthorized")

	// ErrForbidden is returned when the API returns a 403 Forbidden
	ErrForbidden = errors.New("forbidden")

	// ErrNotFound is returned when the API returns a 404 Not Found
	ErrNotFound = errors.New("not found")

	// ErrServerError is returned when the API returns a 5xx error
	ErrServerError = errors.New("server error")

	// ErrInvalidResponse is returned when the API returns an invalid response
	ErrInvalidResponse = errors.New("invalid response")

	// ErrInvalidParameters is returned when invalid parameters are provided
	ErrInvalidParameters = errors.New("invalid parameters")

	// ErrQueryTooLong is returned when the query is too long (>400 chars or >50 words)
	ErrQueryTooLong = errors.New("query too long (max 400 chars or 50 words)")

	// ErrEmptyQuery is returned when an empty query is provided
	ErrEmptyQuery = errors.New("query cannot be empty")

	// ErrUnprocessableEntity is returned when the API returns a 422 Unprocessable Entity
	ErrUnprocessableEntity = errors.New("unprocessable entity")

	// ErrSubscriptionTokenInvalid is returned when the subscription token is invalid
	ErrSubscriptionTokenInvalid = errors.New("invalid subscription token")

	// ErrInvalidEndpoint is returned when an endpoint override is unsafe or malformed.
	ErrInvalidEndpoint = errors.New("invalid endpoint")

	// ErrResponseTooLarge is returned when an API response exceeds the configured safety limit.
	ErrResponseTooLarge = errors.New("response body too large")
)

Functions

func GetUserAgent

func GetUserAgent() string

GetUserAgent returns the user agent string for this library

func GetVersion

func GetVersion() string

GetVersion returns the current version of the client library

func IsAuthError

func IsAuthError(err error) bool

IsAuthError checks if the error is an authentication error

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError checks if the error is a rate limit error

func IsServerError

func IsServerError(err error) bool

IsServerError checks if the error is a server error

func IsUnprocessableEntity

func IsUnprocessableEntity(err error) bool

IsUnprocessableEntity checks if the error is an unprocessable entity error

func ValidateConfig

func ValidateConfig(config *ClientConfig) error

ValidateConfig validates the client configuration

Types

type APIError

type APIError struct {
	StatusCode int    `json:"status_code,omitempty"`
	Message    string `json:"message,omitempty"`
	Err        error  `json:"error,omitempty"`
}

APIError represents an error returned by the Brave Search API

func NewAPIError

func NewAPIError(statusCode int, message string, err error) *APIError

NewAPIError creates a new APIError

func NewHTTPError

func NewHTTPError(resp *http.Response) *APIError

NewHTTPError creates a new APIError from an HTTP response

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the wrapped error

type ButtonResult

type ButtonResult struct {
	Type  string `json:"type"`
	Title string `json:"title"`
	URL   string `json:"url"`
}

ButtonResult represents a button in deep results

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the API client for Brave Search

func NewClient

func NewClient(apiKey string, options ...ClientOption) (*Client, error)

NewClient creates a new Brave Search API client

func (*Client) WebSearch

func (c *Client) WebSearch(ctx context.Context, query string, params *WebSearchParams) (*WebSearchResponse, error)

WebSearch performs a web search

func (*Client) WebSearchNews

func (c *Client) WebSearchNews(ctx context.Context, query string) (*WebSearchResponse, error)

WebSearchNews performs a web search filtered to news results

func (*Client) WebSearchRecent

func (c *Client) WebSearchRecent(ctx context.Context, query string) (*WebSearchResponse, error)

WebSearchRecent performs a web search for recent content

func (*Client) WebSearchSummary

func (c *Client) WebSearchSummary(ctx context.Context, query string) (*WebSearchResponse, error)

WebSearchSummary performs a web search with summary enabled

func (*Client) WebSearchVideos

func (c *Client) WebSearchVideos(ctx context.Context, query string) (*WebSearchResponse, error)

WebSearchVideos performs a web search filtered to video results

func (*Client) WebSearchWithCountry

func (c *Client) WebSearchWithCountry(ctx context.Context, query string, country string) (*WebSearchResponse, error)

WebSearchWithCountry performs a web search with a specific country

func (*Client) WebSearchWithFreshness

func (c *Client) WebSearchWithFreshness(ctx context.Context, query string, freshness string) (*WebSearchResponse, error)

WebSearchWithFreshness performs a web search with a specific freshness setting

func (*Client) WebSearchWithGoggles

func (c *Client) WebSearchWithGoggles(ctx context.Context, query string, goggles string) (*WebSearchResponse, error)

WebSearchWithGoggles performs a web search with a Goggles definition

func (*Client) WebSearchWithGogglesID

func (c *Client) WebSearchWithGogglesID(ctx context.Context, query string, gogglesID string) (*WebSearchResponse, error)

WebSearchWithGogglesID performs a web search with a pre-registered Goggles ID

func (*Client) WebSearchWithLanguage

func (c *Client) WebSearchWithLanguage(ctx context.Context, query string, lang string) (*WebSearchResponse, error)

WebSearchWithLanguage performs a web search with a specific search language

func (*Client) WebSearchWithPagination

func (c *Client) WebSearchWithPagination(ctx context.Context, query string, count, offset int) (*WebSearchResponse, error)

WebSearchWithPagination performs a web search with pagination

func (*Client) WebSearchWithSafeSearch

func (c *Client) WebSearchWithSafeSearch(ctx context.Context, query string, safeSearch string) (*WebSearchResponse, error)

WebSearchWithSafeSearch performs a web search with a specific SafeSearch setting

func (*Client) WebSearchWithUnits

func (c *Client) WebSearchWithUnits(ctx context.Context, query string, units string) (*WebSearchResponse, error)

WebSearchWithUnits performs a web search with specific measurement units

type ClientConfig

type ClientConfig struct {
	APIKey            string
	BaseURL           string
	WebSearchEndpoint string
	Timeout           time.Duration
	MaxRetries        int
	UserAgent         string
	DefaultCountry    string
	DefaultSearchLang string
	DefaultUILang     string
	HTTPClient        *http.Client
}

ClientConfig holds the configuration for the API client

type ClientOption

type ClientOption func(*ClientConfig) error

ClientOption is a function that can be used to configure a Client

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the base URL for the API

func WithConfig

func WithConfig(config *Config) ClientOption

WithConfig creates a new client with the given configuration

func WithDefaultCountry

func WithDefaultCountry(country string) ClientOption

WithDefaultCountry sets the default country for requests

func WithDefaultSearchLanguage

func WithDefaultSearchLanguage(lang string) ClientOption

WithDefaultSearchLanguage sets the default search language for requests

func WithDefaultUILanguage

func WithDefaultUILanguage(lang string) ClientOption

WithDefaultUILanguage sets the default UI language for requests

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithRetries

func WithRetries(retries int) ClientOption

WithRetries sets the maximum number of retries for requests

func WithTimeout

func WithTimeout(seconds int) ClientOption

WithTimeout sets the timeout for requests

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent sets the User-Agent header for requests

func WithWebSearchEndpoint added in v0.3.0

func WithWebSearchEndpoint(endpoint string) ClientOption

WithWebSearchEndpoint sets the endpoint for Web Search requests.

type Config

type Config struct {
	// APIKey is the authentication token for the API
	APIKey string

	// BaseURL is the base URL for API requests
	BaseURL string

	// WebSearchEndpoint is the endpoint for Web Search requests.
	WebSearchEndpoint string

	// HTTPClient is the HTTP client to use for requests
	HTTPClient *http.Client

	// Timeout is the timeout for requests
	Timeout time.Duration

	// MaxRetries is the maximum number of retries for failed requests
	MaxRetries int

	// UserAgent is the User-Agent header to use for requests
	UserAgent string

	// DefaultCountry is the default country code for searches
	DefaultCountry string

	// DefaultSearchLang is the default search language
	DefaultSearchLang string

	// DefaultUILang is the default UI language
	DefaultUILang string
}

Config provides configuration for the Brave Search API client.

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig creates a new default configuration

type DeepResults

type DeepResults struct {
	Buttons []ButtonResult `json:"buttons,omitempty"`
	Social  []SocialResult `json:"social,omitempty"`
	Video   []VideoResult  `json:"video,omitempty"`
	Images  []ImageResult  `json:"images,omitempty"`
	News    []NewsResult   `json:"news,omitempty"`
}

DeepResults represents additional links or features for a search result

type DiscussionResult

type DiscussionResult struct {
	Type           string   `json:"type"`
	Title          string   `json:"title"`
	URL            string   `json:"url"`
	Description    string   `json:"description,omitempty"`
	Age            string   `json:"age,omitempty"`
	PageAge        string   `json:"page_age,omitempty"`
	FamilyFriendly bool     `json:"family_friendly"`
	Language       string   `json:"language,omitempty"`
	Profile        *Profile `json:"profile,omitempty"`
}

DiscussionResult represents an individual discussion result

type Discussions

type Discussions struct {
	Type    string             `json:"type"`
	Results []DiscussionResult `json:"results,omitempty"`
}

Discussions represents forum discussions

type FAQ

type FAQ struct {
	Type    string      `json:"type"`
	Results []FAQResult `json:"results,omitempty"`
}

FAQ represents frequently asked questions

type FAQResult

type FAQResult struct {
	Type     string `json:"type"`
	Question string `json:"question"`
	Answer   string `json:"answer"`
}

FAQResult represents an individual FAQ result

type GraphInfobox

type GraphInfobox struct {
	Type string       `json:"type"`
	Data *InfoboxData `json:"data,omitempty"`
}

GraphInfobox represents an infobox

type ImageResult

type ImageResult struct {
	Type      string     `json:"type"`
	Title     string     `json:"title"`
	URL       string     `json:"url"`
	Source    string     `json:"source,omitempty"`
	Thumbnail *Thumbnail `json:"thumbnail,omitempty"`
	Width     int        `json:"width,omitempty"`
	Height    int        `json:"height,omitempty"`
}

ImageResult represents an image result in deep results

type InfoboxData

type InfoboxData struct {
	Label       string     `json:"label,omitempty"`
	Title       string     `json:"title,omitempty"`
	URL         string     `json:"url,omitempty"`
	Description string     `json:"description,omitempty"`
	Thumbnail   *Thumbnail `json:"thumbnail,omitempty"`
	Attributes  [][]string `json:"attributes,omitempty"`
	Profiles    []Profile  `json:"profiles,omitempty"`
}

InfoboxData represents the data within an infobox

type LocationPOI

type LocationPOI struct {
	Type        string     `json:"type"`
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Address     string     `json:"address,omitempty"`
	Phone       string     `json:"phone,omitempty"`
	URL         string     `json:"url,omitempty"`
	Rating      float64    `json:"rating,omitempty"`
	ReviewCount int        `json:"review_count,omitempty"`
	Thumbnail   *Thumbnail `json:"thumbnail,omitempty"`
}

LocationPOI represents a point of interest

type Locations

type Locations struct {
	Type    string        `json:"type"`
	Results []LocationPOI `json:"results,omitempty"`
}

Locations represents location results

type MetaURL

type MetaURL struct {
	Scheme   string `json:"scheme,omitempty"`
	Netloc   string `json:"netloc,omitempty"`
	Hostname string `json:"hostname,omitempty"`
	Favicon  string `json:"favicon,omitempty"`
	Path     string `json:"path,omitempty"`
}

MetaURL represents metadata about the URL

type MixedResponse

type MixedResponse struct {
	Type string           `json:"type"`
	Main []MixedResultRef `json:"main"`
	Top  []MixedResultRef `json:"top"`
	Side []MixedResultRef `json:"side"`
}

MixedResponse represents a collection of mixed result types

type MixedResultRef

type MixedResultRef struct {
	Type  string `json:"type"`
	Index int    `json:"index"`
	All   bool   `json:"all"`
}

MixedResultRef references a result in another section

type News

type News struct {
	Type    string       `json:"type"`
	Results []NewsResult `json:"results,omitempty"`
}

News represents news results

type NewsResult

type NewsResult struct {
	Type           string     `json:"type"`
	Title          string     `json:"title"`
	URL            string     `json:"url"`
	Description    string     `json:"description,omitempty"`
	Age            string     `json:"age,omitempty"`
	PageAge        string     `json:"page_age,omitempty"`
	FamilyFriendly bool       `json:"family_friendly"`
	Language       string     `json:"language,omitempty"`
	Profile        *Profile   `json:"profile,omitempty"`
	Thumbnail      *Thumbnail `json:"thumbnail,omitempty"`
}

NewsResult represents an individual news result

type Profile

type Profile struct {
	Name     string `json:"name,omitempty"`
	URL      string `json:"url,omitempty"`
	LongName string `json:"long_name,omitempty"`
	Img      string `json:"img,omitempty"`
}

Profile represents profile information associated with a search result

type Query

type Query struct {
	Original             string `json:"original"`
	Altered              string `json:"altered,omitempty"`
	ShowStrictWarning    bool   `json:"show_strict_warning"`
	IsNavigational       bool   `json:"is_navigational"`
	IsNewsBreaking       bool   `json:"is_news_breaking"`
	SpellcheckOff        bool   `json:"spellcheck_off"`
	Country              string `json:"country"`
	BadResults           bool   `json:"bad_results"`
	ShouldFallback       bool   `json:"should_fallback"`
	PostalCode           string `json:"postal_code"`
	City                 string `json:"city"`
	HeaderCountry        string `json:"header_country"`
	MoreResultsAvailable bool   `json:"more_results_available"`
	State                string `json:"state"`
}

Query represents query information

type RateLimit

type RateLimit struct {
	Limit     int
	Remaining int
	Reset     int
}

RateLimit represents rate limit information

type RichHint added in v0.3.0

type RichHint struct {
	Vertical    string `json:"vertical,omitempty"`
	CallbackKey string `json:"callback_key,omitempty"`
}

RichHint contains the callback information for rich search results.

type RichResponse

type RichResponse struct {
	Type string    `json:"type"`
	Hint *RichHint `json:"hint,omitempty"`
}

RichResponse represents rich data enhancements

type Search struct {
	Type           string         `json:"type"`
	Results        []SearchResult `json:"results"`
	FamilyFriendly bool           `json:"family_friendly"`
}

Search represents a collection of web search results

type SearchResult

type SearchResult struct {
	Title          string       `json:"title"`
	URL            string       `json:"url"`
	IsSourceLocal  bool         `json:"is_source_local"`
	IsSourceBoth   bool         `json:"is_source_both"`
	Description    string       `json:"description,omitempty"`
	PageAge        string       `json:"page_age,omitempty"`
	PageFetched    string       `json:"page_fetched,omitempty"`
	Profile        *Profile     `json:"profile,omitempty"`
	Language       string       `json:"language,omitempty"`
	FamilyFriendly bool         `json:"family_friendly"`
	Type           string       `json:"type"`
	Subtype        string       `json:"subtype,omitempty"`
	IsLive         bool         `json:"is_live,omitempty"`
	DeepResults    *DeepResults `json:"deep_results,omitempty"`
	MetaURL        *MetaURL     `json:"meta_url,omitempty"`
	Thumbnail      *Thumbnail   `json:"thumbnail,omitempty"`
	Age            string       `json:"age,omitempty"`
	ExtraSnippets  []string     `json:"extra_snippets,omitempty"`
	ContentType    string       `json:"content_type,omitempty"`
}

SearchResult represents an individual web search result

type SocialResult

type SocialResult struct {
	Type    string `json:"type"`
	Title   string `json:"title"`
	URL     string `json:"url"`
	Snippet string `json:"snippet,omitempty"`
	Profile string `json:"profile,omitempty"`
}

SocialResult represents a social media result in deep results

type Summarizer

type Summarizer struct {
	Type   string `json:"type"`
	Key    string `json:"key,omitempty"`
	Status string `json:"status,omitempty"`
}

Summarizer represents summary results

type Thumbnail

type Thumbnail struct {
	Src      string `json:"src,omitempty"`
	Original string `json:"original,omitempty"`
}

Thumbnail represents an image thumbnail

type VideoResult

type VideoResult struct {
	Type           string     `json:"type"`
	Title          string     `json:"title"`
	URL            string     `json:"url"`
	Description    string     `json:"description,omitempty"`
	Age            string     `json:"age,omitempty"`
	PageAge        string     `json:"page_age,omitempty"`
	FamilyFriendly bool       `json:"family_friendly"`
	Language       string     `json:"language,omitempty"`
	Thumbnail      *Thumbnail `json:"thumbnail,omitempty"`
	Duration       string     `json:"duration,omitempty"`
	EmbedURL       string     `json:"embed_url,omitempty"`
}

VideoResult represents an individual video result

type Videos

type Videos struct {
	Type    string        `json:"type"`
	Results []VideoResult `json:"results,omitempty"`
}

Videos represents video results

type WebSearchParams

type WebSearchParams struct {
	// Required parameters
	Query string `url:"q,omitempty"`

	// Optional parameters
	Country              string `url:"country,omitempty"`
	SearchLang           string `url:"search_lang,omitempty"`
	UILang               string `url:"ui_lang,omitempty"`
	Count                int    `url:"count,omitempty"`
	Offset               int    `url:"offset,omitempty"`
	SafeSearch           string `url:"safesearch,omitempty"`
	Freshness            string `url:"freshness,omitempty"`
	TextDecorations      bool   `url:"text_decorations,omitempty"`
	Spellcheck           bool   `url:"spellcheck,omitempty"`
	ResultFilter         string `url:"result_filter,omitempty"`
	Goggles              string `url:"goggles,omitempty"`
	GogglesID            string `url:"goggles_id,omitempty"`
	Units                string `url:"units,omitempty"`
	ExtraSnippets        bool   `url:"extra_snippets,omitempty"`
	Summary              bool   `url:"summary,omitempty"`
	EnableRichCallback   bool   `url:"enable_rich_callback,omitempty"`
	IncludeFetchMetadata bool   `url:"include_fetch_metadata,omitempty"`
}

WebSearchParams holds the parameters for a web search request

func NewWebSearchParams

func NewWebSearchParams() *WebSearchParams

NewWebSearchParams creates a new WebSearchParams with default values

type WebSearchResponse

type WebSearchResponse struct {
	Type        string         `json:"type"`
	RateLimit   *RateLimit     `json:"-"`
	Discussions *Discussions   `json:"discussions,omitempty"`
	FAQ         *FAQ           `json:"faq,omitempty"`
	Infobox     *GraphInfobox  `json:"infobox,omitempty"`
	Locations   *Locations     `json:"locations,omitempty"`
	Mixed       *MixedResponse `json:"mixed,omitempty"`
	News        *News          `json:"news,omitempty"`
	Query       *Query         `json:"query,omitempty"`
	Videos      *Videos        `json:"videos,omitempty"`
	Web         *Search        `json:"web,omitempty"`
	Summarizer  *Summarizer    `json:"summarizer,omitempty"`
	Rich        *RichResponse  `json:"rich,omitempty"`
}

WebSearchResponse represents the top-level response from the Web Search API

func (*WebSearchResponse) GetFirstResult

func (r *WebSearchResponse) GetFirstResult() *SearchResult

GetFirstResult returns the first web result or nil if no results

func (*WebSearchResponse) GetResultCount

func (r *WebSearchResponse) GetResultCount() int

GetResultCount returns the number of web results

func (*WebSearchResponse) GetWebResults

func (r *WebSearchResponse) GetWebResults() []SearchResult

GetWebResults is a helper function to extract web results from the response

func (*WebSearchResponse) HasMoreResults

func (r *WebSearchResponse) HasMoreResults() bool

HasMoreResults checks if the search has more results available

func (*WebSearchResponse) IsWebResultEmpty

func (r *WebSearchResponse) IsWebResultEmpty() bool

IsWebResultEmpty checks if the web results are empty

Directories

Path Synopsis
examples
simple command
Package main provides a simple example of using the Brave Search API client.
Package main provides a simple example of using the Brave Search API client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL