Build a URL Checker in Go: Concurrency in Practice

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

In the previous article, we explored why Go champions simplicity and lightweight concurrency. Here, we’ll see it in action: we’ll build a URL checker that inspects a list of sites in parallel and reports which ones respond, with what HTTP status code, and how long each took.

The final program takes about 130 lines of code, relies solely on the standard library, and compiles into a single binary. We’ll build it in three steps, observing performance improvements along the way.

What We’re Building

Here is how the program will be used (the sites in this output are just an example):

verificador -archivo sitios.txt -workers 5 -timeout 3s
OK     200   142ms  https://juredev.com
OK     200   310ms  https://go.dev
FALLO  503   1.2s   https://ejemplo-caido.com
FALLO  ---   3s     https://no-existe.invalid  (context deadline exceeded)

4 sitios revisados en 3.1s: 2 OK, 2 con fallo

Setup

You’ll need Go installed (any recent version) and a text file containing one URL per line. Create the project directory:

mkdir verificador && cd verificador
go mod init verificador

And the sitios.txt file:

https://juredev.com
https://go.dev
https://github.com

The code for each step goes into a main.go file inside that folder.

Step 1: The Sequential Version

We start with the simplest approach: iterating through the list and making one request after another. We define a Resultado type to store what we find out about each site, a verificar function, and a loop in main.

package main

import (
	"bufio"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"
)

type Resultado struct {
	URL      string
	Estado   int
	Duracion time.Duration
	Err      error
}

func verificar(url string) Resultado {
	inicio := time.Now()
	resp, err := http.Get(url)
	if err != nil {
		return Resultado{URL: url, Duracion: time.Since(inicio), Err: err}
	}
	defer resp.Body.Close()
	return Resultado{URL: url, Estado: resp.StatusCode, Duracion: time.Since(inicio)}
}

func leerURLs(ruta string) ([]string, error) {
	f, err := os.Open(ruta)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var urls []string
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		if linea := strings.TrimSpace(sc.Text()); linea != "" {
			urls = append(urls, linea)
		}
	}
	return urls, sc.Err()
}

func main() {
	urls, err := leerURLs(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}

	inicio := time.Now()
	for _, url := range urls {
		r := verificar(url)
		fmt.Printf("%d  %v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
	}
	fmt.Printf("\n%d sitios en %v\n", len(urls), time.Since(inicio).Round(time.Millisecond))
}

Two Go nuances emerge here. First, errors are values: http.Get returns (resp, err), and we store the error inside Resultado instead of throwing an exception. Second, defer resp.Body.Close() ensures the response body is closed when exiting the function, no matter what happens.

Run it with go run . sitios.txt. Connection failures appear with status 0 because we aren’t displaying the error yet; we’ll fix that in step 3.

How we benchmarked the execution time. To make tests reproducible, we used a local server that simulates real sites. That makes 10 URLs: six respond in 1 second, one responds instantly, one returns a 503 error, one hangs for 10 seconds, and one rejects the connection. The test server and the script to repeat the benchmarks are in the project repository.

This version takes 16 seconds. Each request waits for the previous one to finish, so the delays add up: six 1s waits plus the 10s hanging site.

Step 2: One Goroutine per Site

Since requests are independent of each other, there’s no reason to wait sequentially. We launch a goroutine for each URL and collect the results through a channel. Only main changes: Resultado, verificar, and leerURLs remain untouched, and we now also import sync.

func main() {
	urls, err := leerURLs(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}

	inicio := time.Now()
	resultados := make(chan Resultado)
	var wg sync.WaitGroup

	for _, url := range urls {
		wg.Add(1)
		go func(u string) {
			defer wg.Done()
			resultados <- verificar(u)
		}(url)
	}

	// Cerramos el canal cuando todas las goroutines terminen.
	go func() {
		wg.Wait()
		close(resultados)
	}()

	for r := range resultados {
		fmt.Printf("%d  %v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
	}
	fmt.Printf("\n%d sitios en %v\n", len(urls), time.Since(inicio).Round(time.Millisecond))
}

There are two key takeaways. The anonymous goroutine at the end waits with wg.Wait() for all goroutines to finish and then closes the channel; without that close, the for range loop below would wait for results indefinitely. Also, results arrive in the order they complete, not in the list order.

The elapsed time drops to 10 seconds: it’s no longer the sum of all delays, but the duration of the slowest site. However, two issues remain:

  • With 10,000 URLs, we would fire 10,000 requests simultaneously, potentially exhausting file descriptors/connections or overwhelming target servers.
  • There is no timeout: a hanging site holds up the entire program. Here it’s 10 seconds; in practice, http.Get could hang indefinitely.

Step 3: Worker Pool and Context

We solve both problems simultaneously. A worker pool limits how many requests run concurrently: a fixed number of goroutines (workers) pull URLs from a channel. Meanwhile, context enforces a maximum timeout on each request.

A Per-Request Timeout

verificar now accepts a context.Context. By constructing the request with http.NewRequestWithContext, if the context expires, Do returns an error and the request is aborted. We also add an OK() method to determine what counts as a success (no error and status code under 400). We will need context and flag imports.

func (r Resultado) OK() bool {
	return r.Err == nil && r.Estado < 400
}

func verificar(ctx context.Context, url string) Resultado {
	inicio := time.Now()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return Resultado{URL: url, Err: err}
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return Resultado{URL: url, Duracion: time.Since(inicio), Err: err}
	}
	defer resp.Body.Close()

	return Resultado{URL: url, Estado: resp.StatusCode, Duracion: time.Since(inicio)}
}

The Worker

Each worker reads URLs from the queue until it closes. For each URL, it creates a context with a timeout, checks the URL, and releases the context via cancel():

func worker(urls <-chan string, resultados chan<- Resultado, timeout time.Duration) {
	for url := range urls {
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		resultados <- verificar(ctx, url)
		cancel()
	}
}

Putting the Pieces Together

main parses CLI flags using the flag package, spins up the workers, feeds the queue, and prints the results:

func main() {
	archivo := flag.String("archivo", "sitios.txt", "archivo con una URL por línea")
	workers := flag.Int("workers", 5, "peticiones simultáneas")
	timeout := flag.Duration("timeout", 3*time.Second, "tiempo máximo por petición")
	flag.Parse()

	if *workers < 1 {
		fmt.Fprintln(os.Stderr, "error: -workers debe ser al menos 1")
		os.Exit(2)
	}

	urls, err := leerURLs(*archivo)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}

	inicio := time.Now()
	cola := make(chan string)
	resultados := make(chan Resultado)

	var wg sync.WaitGroup
	for i := 0; i < *workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			worker(cola, resultados, *timeout)
		}()
	}

	// Alimentamos la cola y cerramos los canales en su momento.
	go func() {
		for _, u := range urls {
			cola <- u
		}
		close(cola)
	}()
	go func() {
		wg.Wait()
		close(resultados)
	}()

	fallos := 0
	for r := range resultados {
		if r.OK() {
			fmt.Printf("OK     %d  %6v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
			continue
		}
		fallos++
		if r.Err != nil {
			fmt.Printf("FALLO  ---  %6v  %s  (%v)\n", r.Duracion.Round(time.Millisecond), r.URL, r.Err)
		} else {
			fmt.Printf("FALLO  %d  %6v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
		}
	}

	fmt.Printf("\n%d sitios revisados en %v: %d OK, %d con fallo\n",
		len(urls), time.Since(inicio).Round(time.Millisecond), len(urls)-fallos, fallos)

	if fallos > 0 {
		os.Exit(1)
	}
}

Alongside main, three groups of goroutines operate: the workers, the goroutine that feeds the queue (closing it when done), and the goroutine that closes resultados once all workers finish. In addition, main exits with status code 1 if any check failed, making the CLI tool easy to integrate into scripts or scheduled jobs. It also rejects a -workers value below 1: with zero workers, nothing would consume the queue, causing the program to mistakenly treat uninspected sites as healthy.

With 3 workers and a 2-second timeout on the same 10 test URLs, here was the output:

OK     200  1.001s  http://127.0.0.1:8099/lento/1
OK     200  1.001s  http://127.0.0.1:8099/lento/2
OK     200  1.002s  http://127.0.0.1:8099/lento/3
OK     200  1.001s  http://127.0.0.1:8099/lento/4
OK     200  1.001s  http://127.0.0.1:8099/lento/5
OK     200  1.001s  http://127.0.0.1:8099/lento/6
OK     200     1ms  http://127.0.0.1:8099/ok
FALLO  ---      0s  http://127.0.0.1:1/no-existe  (... connection refused)
FALLO  503     1ms  http://127.0.0.1:8099/error
FALLO  ---      2s  http://127.0.0.1:8099/colgado  (... context deadline exceeded)

10 sitios revisados en 4.003s: 7 OK, 3 con fallo

(I shortened error messages with ‘…’ to fit the display.) The hanging site no longer stalls us for 10 seconds: after 2 seconds, context cancels the request and it gets flagged as a failure. And we can finally see why the connection-refusing site failed.

VersionHow It WorksTotal Time
1. SequentialOne request at a time16 s
2. One goroutine per siteAll at once, unbounded10 s
3. Worker pool + context3 at a time, 2 s timeout4 s

These timings come from a local server running simulated responses; with real-world sites, the numbers will differ. A note on the table: the drop from 10 s down to 4 s is not due to higher concurrency, since 3 workers offer less parallelism than step 2. What slashes the execution time is the 2-second timeout cutting off the hanging request.

Compiling and Distributing

Generating the binary takes just a single command:

go build -o verificador
./verificador -archivo sitios.txt -workers 5 -timeout 3s

And for a Linux server, cross-compiling from any operating system:

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o verificador-linux

I checked the resulting file: it’s a statically linked ELF binary. Copy it to the server and it just runs, without installing Go or shared libraries. That’s the deployment advantage we discussed in the previous article.

Ideas to Extend It

  • Retries: retry failed requests with exponential backoff.
  • JSON output: using encoding/json, so other tools can consume the results.
  • Periodic checks: using time.Ticker or cron, alerting via email or chat when a site goes down. The exit code 1 already makes scripting simple.
  • Automated testing: using net/http/httptest, spinning up test servers just like the one used for benchmarking.
  • HEAD instead of GET: to verify that a site responds, there’s no need to download the full body. Some servers reject HEAD requests, so you could fallback to GET on failure.
  • Custom User-Agent: some sites block Go’s default User-Agent header; passing a custom header avoids false positives.

In about 130 lines of code and zero external dependencies, we leveraged almost everything that makes Go stand out: goroutines for concurrency, channels for coordination, errors as values, context for deadlines, and a single binary for deployment. Try it out on your own sites and let us know in the comments what you would add.

Complete Code

Here is the final main.go, ready to copy:

If you prefer not to copy the code by hand, clone the project repository: it includes this final program, each of the three steps separately, and the test files.

package main

import (
	"bufio"
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
)

type Resultado struct {
	URL      string
	Estado   int
	Duracion time.Duration
	Err      error
}

func (r Resultado) OK() bool {
	return r.Err == nil && r.Estado < 400
}

func verificar(ctx context.Context, url string) Resultado {
	inicio := time.Now()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return Resultado{URL: url, Err: err}
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return Resultado{URL: url, Duracion: time.Since(inicio), Err: err}
	}
	defer resp.Body.Close()

	return Resultado{URL: url, Estado: resp.StatusCode, Duracion: time.Since(inicio)}
}

func worker(urls <-chan string, resultados chan<- Resultado, timeout time.Duration) {
	for url := range urls {
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		resultados <- verificar(ctx, url)
		cancel()
	}
}

func leerURLs(ruta string) ([]string, error) {
	f, err := os.Open(ruta)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var urls []string
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		if linea := strings.TrimSpace(sc.Text()); linea != "" {
			urls = append(urls, linea)
		}
	}
	return urls, sc.Err()
}

func main() {
	archivo := flag.String("archivo", "sitios.txt", "archivo con una URL por línea")
	workers := flag.Int("workers", 5, "peticiones simultáneas")
	timeout := flag.Duration("timeout", 3*time.Second, "tiempo máximo por petición")
	flag.Parse()

	if *workers < 1 {
		fmt.Fprintln(os.Stderr, "error: -workers debe ser al menos 1")
		os.Exit(2)
	}

	urls, err := leerURLs(*archivo)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}

	inicio := time.Now()
	cola := make(chan string)
	resultados := make(chan Resultado)

	var wg sync.WaitGroup
	for i := 0; i < *workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			worker(cola, resultados, *timeout)
		}()
	}

	// Alimentamos la cola y cerramos los canales en su momento.
	go func() {
		for _, u := range urls {
			cola <- u
		}
		close(cola)
	}()
	go func() {
		wg.Wait()
		close(resultados)
	}()

	fallos := 0
	for r := range resultados {
		if r.OK() {
			fmt.Printf("OK     %d  %6v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
			continue
		}
		fallos++
		if r.Err != nil {
			fmt.Printf("FALLO  ---  %6v  %s  (%v)\n", r.Duracion.Round(time.Millisecond), r.URL, r.Err)
		} else {
			fmt.Printf("FALLO  %d  %6v  %s\n", r.Estado, r.Duracion.Round(time.Millisecond), r.URL)
		}
	}

	fmt.Printf("\n%d sitios revisados en %v: %d OK, %d con fallo\n",
		len(urls), time.Since(inicio).Round(time.Millisecond), len(urls)-fallos, fallos)

	if fallos > 0 {
		os.Exit(1)
	}
}

Keep coding.