9
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

net/httpでSOCKS proxyを扱う

GoはデフォルトではHTTP_PROXY環境変数を使うことでHTTP Proxyを使うことが出来るのですが、SOCKSは対応していません。

hailiang/socksがSOCKSのライブラリを適用してくれているのでTransportに突っ込むことでSOCKS経由で通信することができます。

mkdir -p go-socks-example/src
cd go-socks-exmaple
export GOPATH=`pwd`
go get -u "github.com/hailiang/socks"
package main

import (
    "fmt"
    "github.com/hailiang/socks"
    "io/ioutil"
    "net/http"
)

func main() {
    dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, "127.0.0.1:1080")
    tr := &http.Transport{Dial: dialSocksProxy}
    httpClient := &http.Client{Transport: tr}

    req, _ := http.NewRequest("GET", "http://google.com", nil)
    res, err := httpClient.Do(req)
    if err != nil {
        fmt.Printf("Error: %s\n", err)
        return
    }
    defer res.Body.Close()
    contents, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Printf("Error: %s\n", err)
        return
    }
    fmt.Printf("result: %s\n", contents)
}
# 別ターミナルでSOCKSつくっとく
ssh YOUR_SERVER -D 1080
# 動かす
go run example.go

社内ツールなどはSOCKS経由でアクセスできると色々楽だったりするので、組み込んでおくと捗るかもしれません。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
9
Help us understand the problem. What are the problem?