Skip to content
workers-go
Esc
navigateopen⌘Jpreview
On this page

Outbound fetch

Make outbound HTTP requests, call other workers through Service Bindings, and read incoming request properties.

The cloudflare/fetch package performs outbound requests through the Workers fetch API and reads Cloudflare-specific request properties.

Fetch with an http.Client

fetch.NewClient() creates a client; HTTPClient adapts it to a standard *http.Client you can use as a RoundTripper — for example in a reverse proxy.

fc := fetch.NewClient()
hc := fc.HTTPClient(fetch.RedirectModeFollow)

proxy := httputil.ReverseProxy{
	Transport: hc.Transport,
	Director:  func(r *http.Request) { r.URL = req.URL },
}
proxy.ServeHTTP(w, req)

Redirect modes: fetch.RedirectModeFollow, fetch.RedirectModeError, fetch.RedirectModeManual.

Fetch with RequestInit

For per-request options, build a fetch.Request and call Client.Do with a RequestInit.

req, err := fetch.NewRequest(ctx, http.MethodGet, "https://example.com", nil)
res, err := fc.Do(req, &fetch.RequestInit{
	Redirect: fetch.RedirectModeManual,
})

Service Bindings

A Service Binding calls another worker directly. Declare it in wrangler.toml, resolve it with cloudflare.GetBinding, and pass it to fetch.WithBinding.

services = [
    { binding = "hello", service = "hello" }
]
bind := cloudflare.GetBinding("hello")
fc := fetch.NewClient(fetch.WithBinding(bind))
res, err := fc.HTTPClient(fetch.RedirectModeFollow).Do(req)

Incoming request properties

fetch.NewIncomingProperties(req.Context()) returns the cf object of the incoming request — country, city, ASN, TLS info, colo, bot management, and more.

p, err := fetch.NewIncomingProperties(req.Context())
if err != nil {
	// not running on Cloudflare
}
fmt.Println(p.Country, p.City, p.Colo, p.Asn)

Example projects

Was this page helpful?