LoginSignup
12
9

More than 5 years have passed since last update.

net/httpでSOCKS proxyを扱う

Last updated at Posted at 2014-07-22

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経由でアクセスできると色々楽だったりするので、組み込んでおくと捗るかもしれません。

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9