Skip to content

Google Search API in Go: Fetch Google Results with net/http

Google reports the same page 2 result as position 3, but its real rank is 13. Fetch Google results in Go with net/http and the JustSERP API: typed structs, a 90 second timeout, retries and a bounded goroutine worker pool.

Google Search API in Go: Fetch Google Results with net/http

Misspell a field name in the request body, say contry instead of country, and our API will not complain. Unknown fields are ignored, so you get a clean 200 with results for the wrong market and no hint why. In Go that is easy to rule out for good: put the request in a typed struct and the compiler catches the typo before it ever costs you a call. I'll walk through the JustSERP API in Go: one POST, a JSON answer, and a typed client with timeouts, retries and a bounded worker pool. Everything uses net/http and encoding/json, so there is nothing to install.

Go code calling the JustSERP API with net/http

What you need

  • Go 1.21 or newer. Nothing outside the standard library is used.
  • A JustSERP API key. Sign up, then copy the key from your dashboard.

Keep the key out of your source code and read it from an environment variable:

export JUSTSERP_API_KEY="your-key-here"

Call the API from your server, never from client-side code. Anything shipped to a user's device exposes your key. Run the call in a backend service or a job and hand your own front end the results.

How a request works

You send a keyword and any options as JSON to https://api.justserp.com/v1/search. We fetch the Google results page, parse it, and return clean JSON. One request returns one results page, typically in 2 to 4 seconds. When Google pushes back we retry the fetch before giving up, so a hard query can take over a minute. Your client has to be willing to wait that long, which is why every timeout in this guide is 90 seconds.

On every request we also ask Google for unfiltered, non-personalised results. You get the full list without the "similar results omitted" notice and without anyone's search history shaping it. Nothing is cached on our side, so each call is a fresh fetch.

Diagram: your Go code sends a POST request to JustSERP, which returns parsed JSON

Your first request

Send the key in the X-API-Key header and the search in the JSON body. Only keyword is required. This is a complete program you can run with go run main.go:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	body, _ := json.Marshal(map[string]any{"keyword": "best coffee grinder"})

	req, err := http.NewRequest(http.MethodPost, "https://api.justserp.com/v1/search", bytes.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("X-API-Key", os.Getenv("JUSTSERP_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 90 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data struct {
		OrganicResults []struct {
			Position int    `json:"position"`
			Title    string `json:"title"`
			Link     string `json:"link"`
		} `json:"organic_results"`
	}
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	for _, r := range data.OrganicResults {
		fmt.Println(r.Position, r.Title)
		fmt.Println("   ", r.Link)
	}
}

Always set a timeout, because http.DefaultClient has none and a stuck connection would hang your program forever. Just do not set it too low. If your client hangs up at 30 seconds while we are still working, the call is still counted and you lose the answer. Ninety seconds avoids that.

What comes back: typed structs

The answer is a JSON object. A block only appears when Google showed it on that page, so a missing block simply decodes to a nil slice in Go, which is safe to loop over. These structs cover the main blocks:

type Result struct {
	Position    int    `json:"position"`
	Title       string `json:"title"`
	Link        string `json:"link"`
	Description string `json:"description"`
}

type Meta struct {
	Status    int    `json:"status"`
	Query     string `json:"query"`
	Device    string `json:"device"`
	GoogleURL string `json:"googleURL"`
}

type Response struct {
	Meta             Meta     `json:"meta"`
	OrganicResults   []Result `json:"organic_results"`
	PaidAds          []Result `json:"paid_ads"`
	RelatedQuestions []string `json:"related_questions"`
	RelatedSearch    []string `json:"related_search"`
}

Fields you do not declare, such as knowledge_graph or inline_videos, are ignored until you add them. Some quirks worth knowing: paid_ads is one list in page order with no top or bottom flag, related_questions holds question text only (no answers), and mobile answers have no inline_videos or totalResults.

A reusable client

Instead of repeating the request code, wrap it in one function. The request options live in a struct, and omitempty keeps unset options out of the JSON so the defaults apply. Add these imports to the program: bytes, context, encoding/json, fmt, io, net/http, os and time.

const apiURL = "https://api.justserp.com/v1/search"

type SearchRequest struct {
	Keyword  string `json:"keyword"`
	Country  string `json:"country,omitempty"`
	Language string `json:"language,omitempty"`
	Location string `json:"location,omitempty"`
	Page     int    `json:"page,omitempty"`
	Device   string `json:"device,omitempty"`
	Tbs      string `json:"tbs,omitempty"`
	Nfpr     string `json:"nfpr,omitempty"`
}

type APIError struct {
	Status int
	Body   string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("justserp: status %d: %s", e.Status, e.Body)
}

func Search(ctx context.Context, sr SearchRequest) (*Response, error) {
	ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
	defer cancel()

	payload, err := json.Marshal(sr)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payload))
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-Key", os.Getenv("JUSTSERP_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	if res.StatusCode != http.StatusOK {
		return nil, &APIError{Status: res.StatusCode, Body: string(body)}
	}

	var out Response
	if err := json.Unmarshal(body, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

The context carries the 90 second timeout, and it also lets a caller cancel the request early, for example when a user closes a page or your service shuts down. Keep in mind that cancelling early has the same cost as a short timeout: the call can still be counted.

Advanced parameters

Every option is a field on SearchRequest, and each one you leave empty is omitted from the JSON.

Table of JustSERP request parameters with defaults and descriptions

Country and language

country (default "United States") chooses the Google domain and market, and language (default "English") sets the interface language. Both take full English names such as "United Kingdom" or "Germany", not codes like "UK" or "de". A name we don't recognise is not an error: it quietly falls back to United States and English, and the call is still used. When results look wrong, print res.Meta.GoogleURL and see which Google domain was really used.

res, err := Search(ctx, SearchRequest{Keyword: "assurance auto", Country: "France", Language: "French"})

Local results with location

For "near me" searches a country is too coarse. location targets a city, using Google's canonical name in the form City,Region,Country. We turn the string into Google's uule parameter as-is, without checking it. A misspelled location is not rejected: Google ignores it, you get non-local results, and the call is used. location does not change the domain or language, so send a matching country too. If you already generate uule strings, you can send one as uule, and location wins when both are present.

res, err := Search(ctx, SearchRequest{Keyword: "plumber near me", Country: "United States", Location: "Austin,Texas,United States"})

Pagination, mobile, time filters and exact queries

page: 2 returns the second results page and overrides start: page N becomes start=(N-1)*10. Each page uses one API call. Position restarts at 1 on every page, so the absolute rank is (page-1)*10 + position, assuming Google returned ten organic results on the page, which it does not always do. device: "mobile" returns the phone layout. tbs is passed to Google as it is, so qdr:d means the past day and qdr:w the past week. nfpr: "1" turns off Google's auto-correction. Both tbs and nfpr must be sent as strings, which is why the fields are string and not int.

ranks := map[string]int{}
for page := 1; page <= 3; page++ {
	res, err := Search(ctx, SearchRequest{Keyword: "project management software", Page: page, Device: "mobile"})
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range res.OrganicResults {
		if _, ok := ranks[r.Link]; !ok {
			ranks[r.Link] = (page-1)*10 + r.Position
			fmt.Println(ranks[r.Link], r.Title)
		}
	}
}

news, _ := Search(ctx, SearchRequest{Keyword: "openai announcement", Tbs: "qdr:d", Nfpr: "1"})
fmt.Println(len(news.OrganicResults), "results from the past day")

Set html: true if you also want the raw Google page in an html field. Add HTML bool `json:"html,omitempty"` to the struct and a matching HTML string field to Response. It makes responses much larger, so leave it off unless you need it. The q alias also works in place of keyword, and unknown fields are ignored without a warning.

Handling errors, and what is billed

Check the HTTP status before you read the body. These are the answers you will meet:

StatusMeaningWhat to do
200Success. One API call is used.Read the results.
400Invalid parameters. No call is used.Fix the request. Do not retry it unchanged.
401The API key is missing or invalid.Check the X-API-Key header.
429You have no API calls left.Top up or upgrade your plan.
500The page could not be fetched. No call is used.Retry after a short pause.

A 200 uses a call. A 400, a 500 or another server error does not, and a 401 or 429 never counts. Retrying a failure therefore costs nothing, with one exception: a request your own client abandons is still counted. This wrapper retries a 500 and network errors with a growing delay, and stops straight away on any other API error. A 500 only reaches you after we have retried on our side, so keep your own retry count small. It also needs the errors import.

func SearchWithRetry(ctx context.Context, sr SearchRequest, retries int) (*Response, error) {
	var lastErr error
	for attempt := 0; attempt <= retries; attempt++ {
		res, err := Search(ctx, sr)
		if err == nil {
			return res, nil
		}
		var apiErr *APIError
		if errors.As(err, &apiErr) && apiErr.Status != http.StatusInternalServerError {
			return nil, err // 400, 401 and 429 will not fix themselves
		}
		lastErr = err

		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(time.Duration(1<<attempt) * time.Second): // 1s, 2s, 4s...
		}
	}
	return nil, fmt.Errorf("gave up on %q: %w", sr.Keyword, lastErr)
}

Running many searches with a worker pool

Each search takes a few seconds, so running them in parallel multiplies your throughput. Your plan sets how many requests may be in flight at once: 10 on the Free and Personal plans, 25 on Business and 50 on Enterprise. That counts requests in progress, not requests per second. Keep your worker count at or below that number. Go makes this a short function. It also needs the sync import.

type Outcome struct {
	Keyword string
	Count   int
	Err     error
}

func SearchMany(ctx context.Context, keywords []string, workers int) []Outcome {
	outcomes := make([]Outcome, len(keywords))
	jobs := make(chan int)

	var wg sync.WaitGroup
	for w := 0; w < workers; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := range jobs {
				res, err := SearchWithRetry(ctx, SearchRequest{Keyword: keywords[i]}, 3)
				o := Outcome{Keyword: keywords[i], Err: err}
				if err == nil {
					o.Count = len(res.OrganicResults)
				}
				outcomes[i] = o // each worker writes its own index, so no lock is needed
			}
		}()
	}

	for i := range keywords {
		jobs <- i
	}
	close(jobs)
	wg.Wait()
	return outcomes
}

Exactly workers goroutines run at any time, however long the keyword list is. Results keep the order of the input. Here is a main that ties it together with an overall deadline. It is generous on purpose, because a single request may use up to 90 seconds:

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	keywords := []string{"crm software", "email marketing tool", "invoice app", "seo checker"}
	for _, o := range SearchMany(ctx, keywords, 5) {
		if o.Err != nil {
			fmt.Printf("%-24s error: %v\n", o.Keyword, o.Err)
			continue
		}
		fmt.Printf("%-24s %d organic results\n", o.Keyword, o.Count)
	}
}

Habits that save calls and headaches

  • Call the API from the server and keep the key in an environment variable, never in a repository.
  • Set a 90 second timeout, with context.WithTimeout or http.Client.Timeout, and never rely on http.DefaultClient alone.
  • Reuse one http.Client so connections are pooled across requests.
  • Cache results you will reuse. We do not cache searches, so a repeated search is a repeated call.
  • Keep workers within your plan's concurrency limit, so requests are never rejected for sending too many at once.

Next steps

That covers what you need to put Google data into your Go services. Create a free account for 2,000 free requests, no credit card needed, and try the examples above, or see the pricing when you are ready to scale. Prefer another language? Read the Python version of this guide or the JavaScript version.