ScreenshotNeo

BlogHow-to

How to Load CSS from a URL in Go

Fetch CSS safely in Go with net/http, timeouts, redirect rules, size limits, validation, caching, and troubleshooting.

By the ScreenshotNeo team30 September 20269 min read

How to Load CSS from a URL in Go

Use Go’s net/http package. Build a request, apply a timeout, send it with an http.Client, check both the transport error and HTTP status, read the response body, and close it. The following complete program downloads a stylesheet to a file.

package main

import (
    "context"
    "errors"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strings"
    "time"
)

const maxCSSBytes int64 = 5 << 20 // 5 MiB

func fetchCSS(ctx context.Context, client *http.Client, rawURL string) ([]byte, error) {
    u, err := url.Parse(rawURL)
    if err != nil {
        return nil, fmt.Errorf("parse CSS URL: %w", err)
    }
    if u.Scheme != "https" && u.Scheme != "http" {
        return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme)
    }
    if u.Host == "" {
        return nil, errors.New("CSS URL must include a host")
    }

    req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
    if err != nil {
        return nil, fmt.Errorf("create request: %w", err)
    }
    req.Header.Set("Accept", "text/css, text/plain;q=0.9, */*;q=0.1")

    resp, err := client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("request CSS: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        return nil, fmt.Errorf("CSS server returned %s", resp.Status)
    }
    if resp.ContentLength > maxCSSBytes {
        return nil, fmt.Errorf("CSS response is larger than %d bytes", maxCSSBytes)
    }

    data, err := io.ReadAll(io.LimitReader(resp.Body, maxCSSBytes+1))
    if err != nil {
        return nil, fmt.Errorf("read CSS response: %w", err)
    }
    if int64(len(data)) > maxCSSBytes {
        return nil, fmt.Errorf("CSS response is larger than %d bytes", maxCSSBytes)
    }
    return data, nil
}

func main() {
    cssURL := "https://example.com/styles.css"
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client := &http.Client{Timeout: 15 * time.Second}
    css, err := fetchCSS(ctx, client, cssURL)
    if err != nil {
        panic(err)
    }
    if err := os.WriteFile("styles.css", css, 0644); err != nil {
        panic(err)
    }
    fmt.Printf("saved %d bytes\n", len(css))
}

The official net/http package documentation covers clients, requests, responses, redirects, and timeouts. A request context gives one operation its own cancellation deadline; the client timeout remains a useful upper bound for all requests made by that client.

1. Decide what “load CSS” means

There are two different jobs:

Goal Use
Make a browser apply a stylesheet Emit <link rel="stylesheet" href="https://…/file.css"> in HTML. The browser performs the fetch.
Download, proxy, cache, inspect, or store CSS in a Go program Fetch the URL with net/http, then handle the returned bytes.

Go downloading CSS does not make it available to a browser automatically. If you need browser styling, either keep the original URL in a link element or serve the downloaded bytes from an endpoint with an appropriate content type.

2. Minimal fetch with http.Get

For a short-lived script with no custom policy, http.Get is the smallest working example. Always close the body and check the status; a completed HTTP exchange can still have a 404 or 500 status.

A bounded Go request validates, fetches, checks, and stores stylesheet bytes.
A bounded Go request validates, fetches, checks, and stores stylesheet bytes.
package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    resp, err := http.Get("https://example.com/styles.css")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        panic(fmt.Sprintf("unexpected status: %s", resp.Status))
    }
    css, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(css))
}

Prefer an explicit client and request context in a server, worker, or user-facing tool. The package’s default client has no general request timeout, so a stalled peer can hold work indefinitely.

3. Validate the URL before fetching

Use net/url to parse the input. A remote stylesheet URL normally needs a scheme and host. Permit only schemes your application needs, usually HTTPS, and permit HTTP only when you deliberately support it.

func validateCSSURL(raw string) (*url.URL, error) {
    u, err := url.Parse(raw)
    if err != nil {
        return nil, err
    }
    if u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") {
        return nil, fmt.Errorf("expected an HTTP(S) URL")
    }
    return u, nil
}

url.ParseRequestURI is designed for request-URI syntax, not as a universal validator for arbitrary absolute URLs. Parsing alone is not a security policy.

4. Redirects, headers, authentication, and caching

Redirect policy

http.Client follows redirects by default. If redirects can cross trust boundaries, inspect every destination with CheckRedirect and reject schemes, hosts, or private destinations that your policy does not allow.

client := &http.Client{
    Timeout: 15 * time.Second,
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        if req.URL.Scheme != "https" {
            return fmt.Errorf("redirected to non-HTTPS URL")
        }
        if len(via) >= 5 {
            return fmt.Errorf("too many redirects")
        }
        return nil
    },
}

Headers and credentials

Set an Accept header for CSS. Add an Authorization header or cookies only when the remote server requires them, and never log those values. A custom user agent can help operators identify your service.

req.Header.Set("User-Agent", "my-css-fetcher/1.0")
req.Header.Set("Accept", "text/css, text/plain;q=0.9, */*;q=0.1")
// req.Header.Set("Authorization", "Bearer "+token)

Conditional requests

For repeated downloads, retain ETag and Last-Modified values. Send them as If-None-Match and If-Modified-Since; a 304 response lets you reuse your cached bytes. Bound cache lifetime and invalidate when the source changes.

5. Limit response size and handle encoding

A stylesheet URL can return an HTML error page, an accidentally huge file, or a response with no Content-Length. Check the header when present, then enforce a hard limit while reading. Reading one byte beyond the limit distinguishes an oversized response from a valid response that exactly reaches the cap.

HTTP compression is normally handled by net/http when it adds Accept-Encoding: gzip; the body you read is decompressed. CSS text is commonly UTF-8, but preserve the bytes if you are proxying or storing them. Decode to a string only when your processing requires it.

6. Check content type without trusting it blindly

A correct server usually returns text/css, but a stylesheet endpoint may omit the header and an error endpoint may return HTML. Treat a non-2xx status as the primary failure. For additional protection, inspect Content-Type and reject clearly unrelated types while allowing an explicit compatibility mode for servers that send text/plain.

contentType := resp.Header.Get("Content-Type")
if contentType != "" && !strings.HasPrefix(strings.ToLower(contentType), "text/css") {
    return nil, fmt.Errorf("unexpected Content-Type %q", contentType)
}

Downloading CSS does not require parsing it. If you need selectors, declarations, or at-rules, choose a maintained CSS grammar library based on the CSS versions it supports, error recovery, API, and license. The golang.org/x/net/html package parses HTML; it is not a CSS parser.

7. Server-side proxy example

If your Go service needs to expose fetched CSS to a browser, fetch it with a bounded context and write a deliberate response. Do not turn this into an unrestricted URL proxy.

func cssProxy(w http.ResponseWriter, r *http.Request) {
    raw := r.URL.Query().Get("url")
    u, err := validateCSSURL(raw)
    if err != nil {
        http.Error(w, "invalid CSS URL", http.StatusBadRequest)
        return
    }

    ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
    defer cancel()
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
    if err != nil {
        http.Error(w, "invalid request", http.StatusBadRequest)
        return
    }
    resp, err := (&http.Client{Timeout: 12 * time.Second}).Do(req)
    if err != nil {
        http.Error(w, "upstream fetch failed", http.StatusBadGateway)
        return
    }
    defer resp.Body.Close()
    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        http.Error(w, "upstream returned an error", http.StatusBadGateway)
        return
    }

    w.Header().Set("Content-Type", "text/css; charset=utf-8")
    if _, err := io.CopyN(w, resp.Body, maxCSSBytes+1); err != nil && err != io.EOF {
        return
    }
}

In production, enforce an allowlist or destination policy, apply rate limits, and resolve private, loopback, link-local, and internal addresses according to your threat model. Re-check redirect destinations and consider connection-time controls: a hostname can resolve to a different address later. Neither a parsed URL nor a string allowlist prevents SSRF by itself.

8. Equivalent requests from cURL, Python, and Node.js

These are useful for reproducing an upstream response outside Go.

curl --fail --location --max-time 15 \
  -H 'Accept: text/css' \
  https://example.com/styles.css \
  -o styles.css
import requests

r = requests.get(
    "https://example.com/styles.css",
    headers={"Accept": "text/css"},
    timeout=15,
)
r.raise_for_status()
with open("styles.css", "wb") as f:
    f.write(r.content)
const res = await fetch('https://example.com/styles.css', {
  headers: { Accept: 'text/css' },
  signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
const css = await res.text();

9. Troubleshooting

Symptom Likely cause Fix
context deadline exceeded DNS, connection, or server exceeded the deadline. Use a realistic context and client timeout; inspect DNS and upstream latency.
Go error is nil but the result is unusable The server returned 404, 403, or 500. Check resp.StatusCode before reading or saving bytes.
Saved file contains HTML A login page, bot challenge, or error document was returned. Inspect status, final URL, content type, and a bounded prefix of the body.
Too many redirects A redirect loop or policy crossing occurred. Set CheckRedirect, cap hops, and validate every destination.
CSS appears truncated Your size cap is lower than the stylesheet or the upstream response is incomplete. Increase the cap deliberately, compare byte counts, and retry only idempotent requests.
Browser refuses the proxied stylesheet Incorrect Content-Type, CSP, or CORS policy. Serve text/css, review response headers, and configure the browser policy intentionally.
Private network access is possible User-controlled URLs and redirects are unrestricted. Apply scheme, host, DNS, IP-range, and connection-time egress controls.

10. Performance, reliability, and cost

  • Reuse an http.Client so its transport can reuse connections. Do not create a new client for every request.
  • Use contexts to cancel work when the caller disconnects or a job is superseded.
  • Bound response bytes, redirect hops, concurrency, and retries. Retry transient connection failures with backoff, but avoid retrying permanent 4xx responses.
  • Cache by the canonical URL plus relevant request headers. Honor validators when available.
  • For many independent stylesheets, limit concurrency with a semaphore so DNS, sockets, and memory remain bounded.
  • Downloading CSS has no ScreenshotNeo charge. If you instead render a page to inspect the visual result, browser startup and page loading are separate work; a screenshot API can remove that setup.

11. Or skip the browser setup

If the real goal is a clean image of a page after its CSS has loaded, ScreenshotNeo provides a one-call screenshot API. It removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

A rendered capture can clean page overlays before the final screenshot.
A rendered capture can clean page overlays before the final screenshot.

See the ScreenshotNeo API documentation for all options. This request captures a rendered page rather than downloading raw CSS:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also supports full-page and element capture, dark mode, device and viewport settings, retina scale, custom CSS and JavaScript, waits, request blocking, headers and cookies, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, bulk capture, and PDFs. Every feature is on every plan: 1,000 screenshots per month are free with no card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

12. FAQ

Can Go apply the CSS to an HTML page?

Not by downloading it alone. A browser or rendering engine must parse the HTML and CSS. Go can serve the stylesheet, transform it, or drive a separate browser.

Should I read CSS with io.ReadAll?

Only when the response is bounded and trusted. For remote or user-selected URLs, combine a size limit with a timeout and status check.

Does a 200 response prove the file is CSS?

No. It proves only that the server reported success. Check content type and, when necessary, inspect the bounded body for an HTML error or challenge page.

What is the safest URL parser?

Use net/url to parse, then implement an application-specific policy for schemes, hosts, redirects, DNS, and destination IPs. No parser supplies complete SSRF protection.