This project is the solution for the Multithreading challenge from the Full Cycle Postgraduate Program in Go. The main goal is to apply advanced concurrency concepts such as goroutines, channels, and the select statement to fetch data from multiple APIs simultaneously, accepting only the fastest response.
The project consists of a CLI application that orchestrates a race between two distinct APIs:
-
Simultaneous Requests:
-
Race & Timeout Logic:
- Using the
selectstatement, the application waits for the first API to return a valid response. - A maximum timeout of 1 second is enforced. If no API responds within this limit, a timeout error is displayed.
- Upon a winner, the slower request is discarded via context cancellation to save system resources.
- Using the
-
Data Normalization (DTOs):
- Specific Data Transfer Objects (DTOs) are used to map different JSON structures from each API into a unified
Addressentity, ensuring architectural decoupling.
- Specific Data Transfer Objects (DTOs) are used to map different JSON structures from each API into a unified
Following Go's best practices and the challenge requirements, all code is contained in a single repository on the main branch:
.
βββ main.go # Core logic, concurrency handling, and DTO mapping
βββ go.mod # Go module dependencies
βββ README.md # Documentation
To test the application, provide a valid 8-digit Brazilian CEP as an argument.
- Execute the Application:
Run the following command replacing
<cep>with a real Brazilian zip code number (ex.:01153000):
go run main.go <cep>Note: You can run this command multiple times. Depending on network latency, the winner API (BrasilAPI or ViaCEP) may change, demonstrating the race condition in real-time.
Successful Race Winner:
Winner: BrasilAPI
Address: {CEP:01153000 State:SP City:SΓ£o Paulo Area:Barra Funda Street:Rua Vitorino Carmilo Source:BrasilAPI}
Timeout Reached (Global limit of 1s):
Error: Timeout reached (1s). Neither API responded in time.