Configuring requests | crawler-go | Spatie       

 SPATIE  

crawler-go
==========

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Crawler-go](https://spatie.be/docs/crawler-go/v1)  Configuring-the-crawler  Configuring requests

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/crawler-go/v1) 

  Configuring requests    
- [ Introduction ](https://spatie.be/docs/crawler-go/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/crawler-go/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/crawler-go/v1/questions-issues)
- [ About us ](https://spatie.be/docs/crawler-go/v1/about-us)
- [ Releasing ](https://spatie.be/docs/crawler-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/crawler-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/crawler-go/v1/support-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/crawler-go/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/crawler-go/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/crawler-go/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/crawler-go/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/crawler-go/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/crawler-go/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/crawler-go/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/crawler-go/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/crawler-go/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/crawler-go/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/crawler-go/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/crawler-go/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/crawler-go/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/crawler-go/v1/advanced-usage/graceful-shutdown)

 Configuring requests
====================

###  On this page 

1. [ User agent ](#content-user-agent)
2. [ Extra headers ](#content-extra-headers)
3. [ Timeouts ](#content-timeouts)
4. [ Authentication ](#content-authentication)
5. [ SSL verification ](#content-ssl-verification)
6. [ Proxy ](#content-proxy)
7. [ Cookies ](#content-cookies)
8. [ Query parameters ](#content-query-parameters)
9. [ Retrying failed requests ](#content-retrying-failed-requests)
10. [ HTTP middleware ](#content-http-middleware)
11. [ Redirects ](#content-redirects)
12. [ Streaming responses ](#content-streaming-responses)

Configure requests in the callback passed to `New`. The crawler uses `net/http`, so you can inject an ordinary `*http.Client`, cookie jar or transport without a package-specific adapter.

User agent
--------------------------------------------------------------------------------------

By default, the crawler identifies itself as `*`. Set `c.UserAgent = "MyBot/1.0"` to change this. An explicit `User-Agent` header takes precedence and is also used for robots.txt decisions.

Extra headers
-----------------------------------------------------------------------------------------------

```
c.Headers.Set("Accept-Language", "en-US")
c.Headers.Set("X-Custom-Header", "value")
```

Headers reach every initial request, including robots.txt. Be careful with credentials when external links are in scope. Go's client strips standard sensitive headers on redirects to unrelated domains according to its own policy, not a blanket same-origin rule. Arbitrary secret headers need your own redirect policy.

Timeouts
--------------------------------------------------------------------------------

Defaults are 10 seconds for connection establishment and 10 seconds for the whole HTTP request, including redirects and body reads:

```
c.Client.Timeout = 30 * time.Second
transport := c.Client.Transport.(*http.Transport)
transport.DialContext = (&net.Dialer{Timeout: 5 * time.Second}).DialContext
```

`Start(ctx)` propagates its context to every HTTP request and renderer. A custom renderer must impose its own timeout or honor a deadline in the crawl context.

Authentication
--------------------------------------------------------------------------------------------------

```
c.Headers.Set("Authorization", "Bearer "+token)
```

For Basic authentication, set `Authorization` to `"Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))`, using `encoding/base64`. The header approach also supports custom token schemes. The crawler rejects embedded credentials in URLs. Keep secrets out of logs and source control.

SSL verification
--------------------------------------------------------------------------------------------------------

TLS verification is enabled. Prefer configuring a custom certificate pool for staging. If you must disable verification in a trusted test environment, configure `TLSClientConfig` on a cloned transport with `tls.Config{InsecureSkipVerify: true}`. Never use this for untrusted or production sites.

Proxy
-----------------------------------------------------------------------

```
proxyURL, err := url.Parse("http://proxy-server:8080")
if err != nil {
    return err
}
c.Client.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
```

The default cloned Go transport uses environment proxy settings. An explicit proxy owns its destination and DNS policy.

Cookies
-----------------------------------------------------------------------------

The default client has a cookie jar. Seed cookies for their URL:

```
u, err := url.Parse("https://example.com")
if err != nil {
    return err
}
c.Client.Jar.SetCookies(u, []*http.Cookie{{Name: "session_id", Value: "abc123"}})
```

The jar applies domain, path and secure-cookie rules. Set `Client.Jar = nil` to disable persistence, or provide your own jar.

Query parameters
--------------------------------------------------------------------------------------------------------

```
c.QueryParameters.Set("language", "nl")
```

Defaults overwrite existing values with the same key, including on robots.txt requests. They do not change stored queue identities and are not reattached to redirect targets. Other query keys are preserved. Go's `url.Values.Encode` sorts outgoing query keys. Use headers rather than query strings for secrets where possible.

Retrying failed requests
--------------------------------------------------------------------------------------------------------------------------------

```
c.Retries = 2
c.RetryDelay = 500 * time.Millisecond
```

The default is no retries. Network/request errors and HTTP 5xx responses are retried, not 4xx. Delay increases linearly, so this example waits 500 ms then 1000 ms. All attempts for a URL use one crawl-budget slot. Cancellation interrupts retry waits. No automatic Retry-After handling is added.

HTTP middleware
-----------------------------------------------------------------------------------------------------

Implement `http.RoundTripper` and wrap `Config.Client.Transport` for request and response hooks, logging, caching or tracing. Go has no Guzzle middleware names or untyped client-option map. Transports can run concurrently and must honor the request context. A middleware returning a response must set its body and headers correctly. The crawler closes bodies after bounded reads.

Redirects
-----------------------------------------------------------------------------------

The default client follows at most five redirects and records each destination. For no following:

```
c.Client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
    return http.ErrUseLastResponse
}
```

Scope and robots checks apply to scheduled URLs, not redirect hops. Use `CheckRedirect` for stricter policies.

Streaming responses
-----------------------------------------------------------------------------------------------------------------

HTTP bodies are always streamed into a bounded byte slice and closed. There is no separate streaming option or raw streaming-body callback. Callbacks receive retained bytes, and no body remains open after fetching.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
