Shifter와 함께 사용 Go
몇 분 만에 Shifter의 레지덴셜 및 ISP 프록시를 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", ...}
} 기능
예시
Sticky Session을 사용하는 표준 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를 플루언트 빌더, 자동 재시도, 응답 바인딩으로 감쌉니다. 깔끔한 오류 처리가 필요한 스크래핑 파이프라인에 유용합니다.
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 (headless 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")
} 자주 묻는 질문
Go와 Shifter 사용에 관한 일반적인 질문.
url.Parse로 프록시 URL을 파싱한 다음, http.ProxyURL(proxyURL)을 통해 *http.Transport에 전달하세요. 해당 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
5분 이내에 Shifter의 205M+ 레지덴셜 및 ISP 프록시를 Go 서비스에 추가하세요. net/http, Resty, Colly, chromedp와 함께 작동합니다.