golang 通过代理 post 代码片段 设置超时


package main
import (
    "fmt"
    "log"
    "net"
    "net/http"
    "net/url"
    "strings"
    "time"
)
func main() {
    httpDo()
}
func httpDo() {
    proxy := func(_ *http.Request) (*url.URL, error) {
        return url.Parse("http://120.78.78.141:8888")
    }
    //transport := &http.Transport{Proxy: proxy}
    transport := &http.Transport{
        Proxy: proxy,
        Dial: (&net.Dialer{
            Timeout: 4 * time.Second,
        }).Dial,
        IdleConnTimeout:       4 * time.Second,
        TLSHandshakeTimeout:   4 * time.Second,
        ResponseHeaderTimeout: 4 * time.Second,
    }
    client := &http.Client{
        Timeout:   time.Second * 4,
        Transport: transport,
    }
    var r http.Request
    r.ParseForm()
    r.Form.Add("uuid", "12311")
    bodystr := strings.TrimSpace(r.Form.Encode())
    req, err := http.NewRequest("POST", "http://www.coffiasd.cn/app/test_proxy", strings.NewReader(bodystr))
    if err != nil {
        // handle error
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("User-Agent", "client-sn22")
    resp, err := client.Do(req)
    if err != nil {
        log.Fatalf("failed to listen - %s", err.Error())
    }
    defer resp.Body.Close()
    fmt.Println("Http reurened stats %v", resp.Status)
}

  

posted @ 2018-06-08 14:28  北落师问  阅读(301)  评论(0编辑  收藏  举报