Shifterと一緒に使用する Go
ShifterのレジデンシャルおよびISP ProxyをGoに数分で組み込めます。標準のnet/http、Resty、GoQuery、Colly、および*url.URLを受け取る任意のクライアントに対応しており、SDKは不要です。
クイックスタート
インストール
go get github.com/go-resty/resty/v2 基本的な使い方
package main
import (
"fmt"
"io"
"net/http"
"net/url"
)
func main() {
proxyURL, _ := url.Parse(
"customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443",
)
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
}
resp, _ := client.Get("https://ipinfo.io/json")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
// {"ip": "154.16.xxx.xxx", "city": "New York", "country": "US", ...}
} 機能
例
スティッキーセッションを使用した標準net/http
依存関係ゼロのオプションです。プロキシURLを持つ*http.Transportを構築します。同じクライアントをゴルーチン間で安全に再利用できます。
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
func newClient(country, city string) *http.Client {
sidBytes := make([]byte, 4)
rand.Read(sidBytes)
sid := hex.EncodeToString(sidBytes)
proxyURL, _ := url.Parse(fmt.Sprintf(
"customer-USERNAME-country-%s-city-%s-sid-%s-ttl-300:PASSWORD@p.shifter.io:443",
country, city, sid,
))
return &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 20 * time.Second,
},
}
}
func main() {
c := newClient("uk", "london")
for _, path := range []string{"/login", "/dashboard", "/orders"} {
req, _ := http.NewRequest("GET", "https://example.co.uk"+path, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
resp, err := c.Do(req)
if err != nil {
fmt.Println("error:", err)
continue
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Println(path, resp.StatusCode, len(body), "bytes")
}
} Resty(より使いやすい)
Restyはnet/httpをfluent builder、自動リトライ、レスポンスバインディングでラップします。クリーンなエラーハンドリングが必要なスクレイピングパイプラインに適しています。
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
func main() {
client := resty.New().
SetProxy("customer-USERNAME-country-de-sid-456DEF:PASSWORD@p.shifter.io:443").
SetRetryCount(3).
SetRetryWaitTime(2_000_000_000). // 2s in ns
SetHeader("User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/537.36")
var products []Product
resp, err := client.R().
SetResult(&products).
Get("https://api.example.de/products")
if err != nil || !resp.IsSuccess() {
fmt.Println("error:", err, resp.Status())
return
}
for _, p := range products {
fmt.Printf("%d %s — %.2f EUR\n", p.ID, p.Name, p.Price)
}
} Colly(スクレイピングフレームワーク)
CollyはデファクトスタンダードのGoスクレイピングライブラリである。SetProxy()でプロキシを設定すると、スパイダーが行うすべてのリクエストがShifterを経由してルーティングされる。
package main
import (
"fmt"
"log"
"github.com/gocolly/colly/v2"
)
func main() {
c := colly.NewCollector(
colly.AllowedDomains("example.com"),
colly.UserAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"),
)
if err := c.SetProxy(
"customer-USERNAME-country-fr-city-paris-sid-789GHI:PASSWORD@p.shifter.io:443",
); err != nil {
log.Fatal(err)
}
c.OnHTML("article.post", func(e *colly.HTMLElement) {
fmt.Println(e.ChildText("h2"), "->", e.ChildAttr("a", "href"))
})
c.OnError(func(r *colly.Response, err error) {
fmt.Printf("error %d: %v\n", r.StatusCode, err)
})
c.Visit("https://example.com/blog")
} chromedp(ヘッドレスChromium)
JavaScriptがレンダリングされる対象に対し、Shifterを通じて実際のChromiumインスタンスを操作できます。chromedpはChromeのCDPプロトコルを使用するため、Seleniumへの依存は不要です。
package main
import (
"context"
"fmt"
"time"
"github.com/chromedp/chromedp"
)
func main() {
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.ProxyServer("http://p.shifter.io:443"),
chromedp.Flag("headless", true),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
var html string
err := chromedp.Run(ctx,
// chromedp doesn't natively prompt for proxy auth — use a Chrome
// extension or run a sidecar that injects credentials, or use
// Shifter's IP-whitelist auth instead of user/pass.
chromedp.Navigate("https://example.com"),
chromedp.WaitVisible("body", chromedp.ByQuery),
chromedp.OuterHTML("html", &html),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(len(html), "bytes")
} よくある質問
Shifter と Go の併用に関するよくある質問。
url.ParseでプロキシURLを解析し、http.ProxyURL(proxyURL)を通じて*http.Transportに渡してください。そのトランスポートを*http.Clientに設定します。クライアントはゴルーチン間で安全に共有でき、コネクションを自動的に再利用します。
resty.New().SetProxy(proxyURL)を呼び出します。Restyが基盤となるトランスポートを処理します。プロキシURLの形式は`http://USER:PASS@p.shifter.io:443`です。本番環境向けのスクレイピングにはSetRetryCountとSetTimeoutをチェーンすることもできます。
はい。コレクターでc.SetProxy(proxyURL)を呼び出すだけで、CollyはすべてのリクエストをShifter経由でルーティングします。複数のセッション間でラウンドロビンを行うにはSetProxyFuncを使用するか、並列スクレイピング用にスパイダーごとに一意のsidを持つShifter URLを渡してください。
プロキシのユーザー名にセッションIDを追加してください。例:`customer-USERNAME-country-us-sid-123ABC`。同じプロキシURLを使用するすべてのGoリクエストは同じレジデンシャルIPを再利用します。`ttl-N`を追加すると、そのIPをN秒まで固定できます。
はい。ExecAllocatorオプションでchromedp.ProxyServerを指定してchromedpを使用してください。ユーザー名とパスワードによる認証には、ShifterのIPホワイトリストと組み合わせてください。Chromeはサイドカー拡張機能なしではヘッドレスモードでプロキシ認証情報を求めません。
SDKは不要です。ShifterはプレーンなHTTPおよびSOCKS5に対応しています。既存のトランスポートを`p.shifter.io:443`に向けるだけです。これによりgo.modをベンダーロックインから解放し、エコシステム内の任意のHTTPクライアントで動作します。
でShifterを使い始める Go
Shifterの2億500万件以上のレジデンシャル・ISPプロキシを5分以内にGoサービスに追加できます。net/http・Resty・Colly・chromedpに対応しています。