源码片段

一些常用源码

proxy

 1package main
 2
 3import (
 4    "context"
 5    "fmt"
 6    "io/ioutil"
 7    "net"
 8    "net/http"
 9    "golang.org/x/net/proxy"
10)
11
12func main() {
13    proxyUrl := "127.0.0.1:1885"
14    dialer, err := proxy.SOCKS5("tcp", proxyUrl, nil, proxy.Direct)
15    dialContext := func(ctx context.Context, network, address string) (net.Conn, error) {
16        return dialer.Dial(network, address)
17    }
18    transport := &http.Transport{DialContext: dialContext,
19        DisableKeepAlives: true}
20    cl := &http.Client{Transport: transport}
21
22    resp, err := cl.Get("https://discovery.linuxcrypt.cn/api/ip")
23    if err != nil {
24        panic(err)
25    }
26    body, err := ioutil.ReadAll(resp.Body)
27    // TODO work with the response
28    if err != nil {
29        fmt.Println("body read failed")
30    }
31    fmt.Println(string(body))
32}