net/http package by configuring a custom http.Transport.
Basic Setup
The key to using a proxy with authentication in Go is to create a customhttp.Client with a Transport that has its Proxy field set.
basic_setup.go
Real-World Example: Scraping Hacker News Headlines
Let’s build a simple but efficient Go application to scrape the titles of the top stories from the Hacker News homepage (news.ycombinator.com). This is a classic scraping target.
This example demonstrates how to create a reusable function to perform the scraping, making it easy to adapt for other targets. We will target Hacker News as if we were in the United Kingdom (GB).
This example uses the
goquery package for easy HTML parsing, similar to jQuery. Install it with:
go get github.com/PuerkitoBio/goqueryhn_scraper.go
How to Run
- Make sure you have Go installed.
- Install the
goquerypackage:go get github.com/PuerkitoBio/goquery - Save the code as
hn_scraper.go. - Run from your terminal:
go run hn_scraper.go
Expected Output
Terminal