Usage | robots-txt-go | Spatie       

 SPATIE  

robots-txt-go
=============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Robots-txt-go](https://spatie.be/docs/robots-txt-go/v1)  Usage

 Version   v1      

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

  Usage    
- [ Introduction ](https://spatie.be/docs/robots-txt-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/robots-txt-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/robots-txt-go/v1/usage)
- [ Testing ](https://spatie.be/docs/robots-txt-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/robots-txt-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/robots-txt-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/robots-txt-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Checking a page ](#content-checking-a-page)
2. [ Parsing robots.txt ](#content-parsing-robotstxt)
3. [ Robots meta tags ](#content-robots-meta-tags)
4. [ X-Robots-Tag headers ](#content-x-robots-tag-headers)

Checking a page
-----------------------------------------------------------------------------------------------------

```
checker := robots.Robots{}

mayIndex, err := checker.MayIndex(ctx, "https://www.spatie.be/nl/admin")
mayFollow, err := checker.MayFollowOn(ctx, "https://www.spatie.be/nl/admin")
```

Examples assume a `context.Context` named `ctx`. Handle each returned error before using its result.

`MayIndex` first checks robots.txt. If crawling is allowed, it reads the page and checks its robots meta tag and global X-Robots-Tag headers. `MayFollowOn` checks only the page's meta tag and global headers, not robots.txt.

You can also specify a user agent:

```
checker := robots.Robots{UserAgent: "UserAgent007"}
```

`MayIndex(ctx, url, "google")` overrides robots.txt rule selection for one call. This does not change the HTTP User-Agent or select agent-specific response headers. Inspect `Headers` directly when you need those.

By default, `Robots` will look for a `robots.txt` file on `https://host.com/robots.txt`. The page's scheme, host and port are preserved, without credentials, query or fragment. Another location can be specified like so:

```
checker := robots.Robots{}
txt, err := checker.ReadTxt(ctx, "https://www.spatie.be/robots-custom.txt")
if err != nil {
    return err
}
checker.Txt = txt
```

Pass `"public/robots.txt"` to read a local file instead. Use `ParseTxt` for already fetched content:

```
checker := robots.Robots{
    Txt: robots.ParseTxt("User-agent: *\nDisallow: /admin"),
}
allowed, err := checker.MayIndex(ctx, "https://www.spatie.be/admin") // false, nil, no page request
```

`Txt` accepts any implementation of `Policy`, whose method is `Allows(string, ...string) bool`. This replaces PHP subclass customization at the decision boundary. Set `Client` to your own `*http.Client` for custom transports, timeouts, proxies or redirect policies. Configure the checker before sharing it between goroutines. The zero value is ready to use. No global robots.txt cache is maintained.

All I/O accepts context cancellation. The default client has a 60-second whole-request timeout and follows up to ten redirects. Only the final response's headers are inspected. Fetch only trusted URLs. These methods do not filter private network destinations.

Parsing robots.txt
------------------------------------------------------------------------------------------------------------

```
txt := robots.ParseTxt(`
  User-agent: *
  Disallow: /admin
  Crawl-delay: 1.5
`)

txt.Allows("/admin", "google") // false
txt.WhyDisallows("/admin", "google") // []robots.Disallow{{UserAgent: "*", BasePath: "/admin"}}
txt.CrawlDelay() // "1.5", true
```

`Allows(url)` uses the wildcard agent. `Allows(url, userAgent)` accepts paths or full URLs, includes query strings, even an empty `?`, and excludes fragments. Paths are case-sensitive and percent escapes are retained. `*` matches any number of characters, and a final `$` anchors a pattern to the end. The longest matching rule wins, with an allow winning ties. Pattern weights count bytes, including `*` and `$`.

As learned in the Rust port, absolute URLs without a path use `/` to match the actual HTTP request target. For example, `https://example.com?download=1` is checked as `/?download=1`. PHP leaves the path empty in that case.

Group selection follows these rules:

- Agent names are matched exactly after trimming and lowercasing.
- When no group matches, the wildcard group is used.
- Allow and disallow group selection are independent. An exact group without allow entries can still use the wildcard group's allows.
- Repeated groups replace previous rules rather than merging them.
- Empty directives, full-line comments and CRLF or LF line endings are accepted. Like PHP, inline comments are not stripped, and unknown directives are also parsed as literal paths. This is a compatibility parser, not a complete RFC 9309 implementation.

For partial user-agent matching:

```
txt := robots.ParseTxt(content).WithPartialMatches()
txt.Allows("/no-agents", "Mozilla/5.0 (compatible Bot/1.1)")
```

Partial matching combines all contained agent names and the wildcard group. Chain `IgnoreGlobalGroup()` to exclude wildcard rules and delays. `IncludeGlobalGroup()` restores them. `ExactMatchesOnly()` restores exact rule matching. These configuration methods return copies, leaving the original unchanged. Keep the returned value. Parsed values may be shared safely between goroutines.

`CrawlDelay("bing")` returns an exact agent's delay with wildcard fallback, regardless of partial rule matching. Delays remain strings so fractional values such as `"1.5"` are preserved. The second return value is false when no delay exists.

`WhyDisallows(path, userAgent)` returns nil when allowed, or a slice of `Disallow` reasons. Reasons use literal prefix checks, list the exact agent before the global group, and do not normalize the diagnostic agent argument. They do not expand wildcard patterns and can include global reasons even when the global group is ignored. A denied path can have an empty non-nil slice. Use `Allows` for the decision.

`ParseTxt(content)` always parses literal content, without PHP's URL autodetection. `checker.ReadTxt(ctx, source)` loads a file or HTTP(S) URL and returns loading errors explicitly. Handle these errors yourself. During automatic discovery only, `MayIndex` treats an unreadable robots.txt as empty and allows crawling, matching PHP. Context cancellation is never swallowed. Page, meta and header loading errors are always returned.

Robots meta tags
--------------------------------------------------------------------------------------------------------

```
meta := robots.ParseMeta(`<meta name="robots" content="noindex, nofollow">`)
meta.MayIndex() // false
meta.MayFollow() // false
meta.Noindex() // true
meta.Nofollow() // true
```

`checker.ReadMeta(ctx, source)` reads HTML from a file or URL. Only the first tag starting with `<meta name="robots"` is considered. Single quotes, mixed case and multiline attributes work. Attributes in a different order do not match. Only `noindex` and `nofollow` substrings are checked. `none` is not expanded in meta tags.

X-Robots-Tag headers
--------------------------------------------------------------------------------------------------------------------

```
headers := robots.ParseHeaders(http.Header{
    "X-Robots-Tag": {"nofollow", "google: noindex, nofollow"},
})
headers.MayIndex() // true
headers.MayFollow() // false
headers.MayIndex("google") // false
headers.MayFollow("google") // false
```

Import `net/http` for `http.Header`. `none` disables both indexing and following in headers. The `Noindex`, `Nofollow` and `None` predicates accept an optional agent. Header names and directives are case-insensitive, but agent keys are case-sensitive. Repeated values for a header are processed in order. The last value for a given agent replaces earlier ones. Specific-agent directives replace global directives, including explicit false values. Search engines can apply different rules.

Use `checker.ReadHeaders(ctx, url)` to fetch a response's headers. Local files have no headers. Sources are local paths or HTTP(S) URLs. Unsupported URL schemes and PHP stream wrappers are not supported. HTTP responses outside 200–299 return errors after redirects have been followed.

 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)
