本文整理汇总了Golang中net/http.Transport类的典型用法代码示例。如果您正苦于以下问题:Golang Transport类的具体用法?Golang Transport怎么用?Golang Transport使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: initTransport
// Initialise the http.Transport for go1.7+
func (ci *ConfigInfo) initTransport(t *http.Transport) {
t.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
return dialContextTimeout(ctx, network, address, ci.ConnectTimeout, ci.Timeout)
}
t.IdleConnTimeout = 60 * time.Second
t.ExpectContinueTimeout = ci.ConnectTimeout
}
示例2: NewClient
func (auth *Auth) NewClient() *http.Client {
var client *http.Client
var transport *http.Transport
if auth.Settings["insecure"] != "" || auth.Settings["proxy_host"] != "" {
transport = &http.Transport{}
}
if auth.Settings["insecure"] != "" {
//FIXME
os.Setenv("HTTP_PROXY", "http://127.0.0.1:10004")
os.Setenv("NO_PROXY", "")
var config *tls.Config = &tls.Config{
InsecureSkipVerify: true,
}
transport.TLSClientConfig = config
}
if auth.Settings["proxy_host"] != "" {
turl, _ := url.Parse("http://" + auth.Settings["proxy_host"] + ":" + auth.Settings["proxy_port"])
transport.Proxy = http.ProxyURL(turl)
}
if auth.Settings["insecure"] != "" || auth.Settings["proxy_host"] != "" {
client = &http.Client{
Jar: auth.CookieJar,
Transport: transport,
}
} else {
client = &http.Client{
Jar: auth.CookieJar,
}
}
return client
}
示例3: main
func main() {
transport := new(http.Transport)
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := new(http.Client)
client.Transport = transport
url := "https://10.80.65.70:9443/rest/agent/1a5dc1ef-f0e6-4aad-839a-a7880d539e8d"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
creds := convertCredentials("admin", "admin")
req.Header.Add("Authorization", "Basic "+creds)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println(resp)
}
示例4: configureTransport
func configureTransport(t1 *http.Transport) error {
connPool := new(clientConnPool)
t2 := &Transport{ConnPool: noDialClientConnPool{connPool}}
if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
return err
}
if t1.TLSClientConfig == nil {
t1.TLSClientConfig = new(tls.Config)
}
if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
}
upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
cc, err := t2.NewClientConn(c)
if err != nil {
c.Close()
return erringRoundTripper{err}
}
connPool.addConn(authorityAddr(authority), cc)
return t2
}
if m := t1.TLSNextProto; len(m) == 0 {
t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
"h2": upgradeFn,
}
} else {
m["h2"] = upgradeFn
}
return nil
}
示例5: login
func login(c *cli.Context) {
println("echo login,", c.Args().Get(0), c.Args().Get(1))
// client := &http.Client{}
reqest, _ := http.NewRequest("GET", "https://passport.baidu.com", nil)
reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
reqest.Header.Set("Accept-Encoding", "gzip, deflate, sdch")
reqest.Header.Set("Accept-Language", "en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4")
reqest.Header.Set("Connection", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36")
transport := http.Transport{}
response, err := transport.RoundTrip(reqest)
if err != nil {
// t.Fatal(err)
}
// // Check if you received the status codes you expect. There may
// // status codes other than 200 which are acceptable.
// if resp.StatusCode != 200 && resp.StatusCode != 302 {
// t.Fatal("Failed with status", resp.Status)
// }
// response,_ := client.Do(reqest)
if response.StatusCode == 302 {
// body, _ := ioutil.ReadAll(response.Body)
// bodystr := string(body);
fmt.Println("cookie: ", response.Cookies())
} else {
fmt.Println("error, code=", response.StatusCode)
}
println("login done")
}
示例6: send
// send sends a request, kills it after passed timeout and writes the result to passed channel
func send(httpClient *http.Client, tr *http.Transport, req request, timeout time.Duration, resp chan request) {
if *debug {
fmt.Println("Sending a request to", req.httpReq.URL)
}
// Send the HTTP request in it's own goroutine using a HTTP client to be able to abort the request if reached timeout
go func() {
start := time.Now()
resp, err := httpClient.Do(req.httpReq)
if err != nil {
req.err = err
} else {
req.StatusCode = resp.StatusCode
req.Duration = time.Since(start)
resp.Body.Close()
}
// Indicate the request is finished
close(req.done)
}()
// Either the request finished, or the timeout triggers
select {
case <-req.done:
// Request is done, please continue
case <-time.After(timeout):
req.Duration = timeout
// Manually cancel the request in flight
tr.CancelRequest(req.httpReq)
req.err = errTimeout
}
// Send back on the response channel
resp <- req
}
示例7: New
// New creates a new Firebase reference
func New(url string) *Firebase {
var tr *http.Transport
tr = &http.Transport{
DisableKeepAlives: true, // https://code.google.com/p/go/issues/detail?id=3514
Dial: func(network, address string) (net.Conn, error) {
start := time.Now()
c, err := net.DialTimeout(network, address, TimeoutDuration)
tr.ResponseHeaderTimeout = TimeoutDuration - time.Since(start)
return c, err
},
}
var client *http.Client
client = &http.Client{
Transport: tr,
CheckRedirect: redirectPreserveHeaders,
}
return &Firebase{
url: sanitizeURL(url),
params: _url.Values{},
client: client,
stopWatching: make(chan struct{}),
}
}
示例8: worker
// Worker
func worker(t *http.Transport, reqChan chan *http.Request, respChan chan Response) {
for req := range reqChan {
resp, err := t.RoundTrip(req)
r := Response{resp, err}
respChan <- r
}
}
示例9: New
// Creates a new Client with the provided options.
func New(o Options) (*Client, error) {
if len(o.Endpoints) == 0 {
return nil, missingEtcdEndpoint
}
if o.Timeout == 0 {
o.Timeout = defaultTimeout
}
httpClient := &http.Client{Timeout: o.Timeout}
if o.Insecure {
var transport *http.Transport
if dt, ok := http.DefaultTransport.(*http.Transport); ok {
dtc := *dt
transport = &dtc
} else {
transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second}).Dial,
TLSHandshakeTimeout: 10 * time.Second}
}
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
httpClient.Transport = transport
}
return &Client{
endpoints: o.Endpoints,
routesRoot: o.Prefix + routesPath,
client: httpClient,
etcdIndex: 0}, nil
}
示例10: image
func image(command *bot.Cmd, matches []string) (msg string, err error) {
client := &http.Client{}
request, _ := http.NewRequest("GET", fmt.Sprintf(imageURL, url.QueryEscape(matches[1])), nil)
request.Header.Set("Ocp-Apim-Subscription-Key", bot.Config.Bing)
response, _ := client.Do(request)
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
var results ImageResults
json.Unmarshal(body, &results)
if err != nil {
return fmt.Sprintf("No results for %s", matches[1]), nil
}
if len(results.Value) == 0 {
return fmt.Sprintf("No results for %s", matches[1]), nil
}
pageURL := results.Value[0].ContentURL
transport := http.Transport{}
request, _ = http.NewRequest("HEAD", pageURL, nil)
response, _ = transport.RoundTrip(request)
pageURL = response.Header.Get("Location")
output := fmt.Sprintf("Bing | %s | %s", matches[1], pageURL)
return output, nil
}
示例11: NewClient
// Creates a new Infoblox client with the supplied user/pass configuration.
// Supports the use of HTTP proxies through the $HTTP_PROXY env var.
// For example:
// export HTTP_PROXY=http://localhost:8888
//
// When using a proxy, disable TLS certificate verification with the following:
// sslVerify = false
func NewClient(host, username, password string, sslVerify bool) *Client {
var (
req, _ = http.NewRequest("GET", host, nil)
proxy, _ = http.ProxyFromEnvironment(req)
transport *http.Transport
tlsconfig *tls.Config
)
tlsconfig = &tls.Config{
InsecureSkipVerify: !sslVerify,
}
if tlsconfig.InsecureSkipVerify {
fmt.Println("WARNING: SSL cert verification disabled!")
}
transport = &http.Transport{
TLSClientConfig: tlsconfig,
}
if proxy != nil {
transport.Proxy = http.ProxyURL(proxy)
}
return &Client{
Host: host,
HttpClient: &http.Client{
Transport: transport,
},
Username: username,
Password: password,
}
}
示例12: ServeHTTP
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
transport := new(http.Transport)
h, ok := w.(http.Hijacker)
if !ok {
return errors.New("Unable to hijack connection")
}
r.Host = srv.addr
r.URL.Host = r.Host
if len(r.URL.Scheme) == 0 {
r.URL.Scheme = "http"
}
response, err := transport.RoundTrip(r)
if err != nil {
return err
}
conn, _, err := h.Hijack()
if err != nil {
return err
}
defer conn.Close()
defer response.Body.Close()
return response.Write(conn)
}
示例13: RoundTrip
func (r exampleDomainRewriter) RoundTrip(req *http.Request) (resp *http.Response, err error) {
req.URL.Scheme = "http"
req.URL.Host = r.RewriteURL.Host
t := http.Transport{}
return t.RoundTrip(req)
}
示例14: HandleHttpRequest
func (this *RequestHandler) HandleHttpRequest(transport *http.Transport, address string) (*http.Response, error) {
this.request.URL.Scheme = "http"
this.request.URL.Host = address
if host, _, err := net.SplitHostPort(this.request.RemoteAddr); err == nil {
xForwardFor := append(this.request.Header["X-Forwarded-For"], host)
this.request.Header.Set("X-Forwarded-For", strings.Join(xForwardFor, ", "))
} else {
log.Println("set X-Forwarded-For error:", err)
}
if _, ok := this.request.Header[http.CanonicalHeaderKey("X-Request-Start")]; !ok {
this.request.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/1e6, 10))
}
this.request.Close = true
this.request.Header.Del("Connection")
response, err := transport.RoundTrip(this.request)
if err != nil {
return response, err
}
for k, vv := range response.Header {
for _, v := range vv {
this.response.Header().Add(k, v)
}
}
return response, err
}
示例15: NewProxyAuthTransport
func NewProxyAuthTransport(rawTransport *http.Transport, customHeaders http.Header) (*ProxyAuthTransport, error) {
dialFn := rawTransport.Dial
if dialFn == nil {
dialFn = net.Dial
}
tr := &ProxyAuthTransport{Dial: dialFn, CustomHeaders: customHeaders}
proxyUrlFn := rawTransport.Proxy
if proxyUrlFn != nil {
wrappedDialFn := tr.wrapTransportDial()
rawTransport.Dial = wrappedDialFn
proxyUrl, err := proxyUrlFn(nil)
if err != nil {
return nil, err
}
if proxyUrl.Scheme != "http" {
return nil, fmt.Errorf("Only HTTP proxy supported, for SOCKS use http.Transport with custom dialers & upstreamproxy.NewProxyDialFunc")
}
if proxyUrl.User != nil {
tr.Username = proxyUrl.User.Username()
tr.Password, _ = proxyUrl.User.Password()
}
// strip username and password from the proxyURL because
// we do not want the wrapped transport to handle authentication
proxyUrl.User = nil
rawTransport.Proxy = http.ProxyURL(proxyUrl)
}
tr.Transport = rawTransport
return tr, nil
}