// WithHTTPClient configures a Maps API client with a http.Client to make requests over. func WithHTTPClient(c *http.Client) ClientOption { return func(client *Client) error { if _, ok := c.Transport.(*transport); !ok { t := c.Transport if t != nil { c.Transport = &transport{Base: t} } else { c.Transport = &transport{Base: http.DefaultTransport} } } client.httpClient = c return nil } }
func fiddler2_enable(client *http.Client, proxys string) { transport := &http.Transport{} http_proxy := url.URL{} proxy, _ := http_proxy.Parse(proxys) transport.Proxy = http.ProxyURL(proxy) client.Transport = transport }
// NewRemoteContext returns a context that gives access to the production // APIs for the application at the given host. All communication will be // performed over SSL unless the host is localhost. func NewRemoteContext(host string, client *http.Client) (appengine.Context, error) { // Add an appcfg header to outgoing requests. t := client.Transport if t == nil { t = http.DefaultTransport } client.Transport = &headerAddingRoundTripper{t} url := url.URL{ Scheme: "https", Host: host, Path: "/_ah/remote_api", } if host == "localhost" || strings.HasPrefix(host, "localhost:") { url.Scheme = "http" } u := url.String() appID, err := getAppID(client, u) if err != nil { return nil, fmt.Errorf("unable to contact server: %v", err) } return &context{ client: client, url: u, appID: appID, }, nil }
func (c *PleskApiClient) Request(request string) (response string, err error) { url := fmt.Sprintf("%s://%s:%d/enterprise/control/agent.php", c.protocol, c.host, c.port) req, err := http.NewRequest("POST", url, strings.NewReader(request)) if err != nil { return } req.Header.Add("Content-type", "text/xml") req.Header.Add("HTTP_PRETTY_PRINT", "TRUE") if c.secretKey != "" { req.Header.Add("KEY", c.secretKey) } else { req.Header.Add("HTTP_AUTH_LOGIN", c.login) req.Header.Add("HTTP_AUTH_PASSWD", c.password) } client := http.Client{} if c.InsecureSkipVerify { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client.Transport = tr } resp, err := client.Do(req) if err != nil { return } defer resp.Body.Close() bytes, err := ioutil.ReadAll(resp.Body) response = string(bytes) return }
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) }
// NewRemoteContext returns a context that gives access to the production // APIs for the application at the given host. All communication will be // performed over SSL unless the host is localhost. func NewRemoteContext(host string, client *http.Client) (context.Context, error) { // Add an appcfg header to outgoing requests. t := client.Transport if t == nil { t = http.DefaultTransport } client.Transport = &headerAddingRoundTripper{t} url := url.URL{ Scheme: "https", Host: host, Path: "/_ah/remote_api", } if host == "localhost" || strings.HasPrefix(host, "localhost:") { url.Scheme = "http" } u := url.String() appID, err := getAppID(client, u) if err != nil { return nil, fmt.Errorf("unable to contact server: %v", err) } rc := &remoteContext{ client: client, url: u, } ctx := internal.WithCallOverride(context.Background(), rc.call) ctx = internal.WithLogOverride(ctx, rc.logf) ctx = internal.WithAppIDOverride(ctx, appID) return ctx, nil }
// Create a new client for making http requests against a Jazz server with the provided credentials // The client will execute the requests authenticating somewhat transparently when needed func NewClient(userID string, password string) (*Client, error) { jClient := &Client{} jClient.userID = userID jClient.password = password options := cookiejar.Options{ PublicSuffixList: publicsuffix.List, } jar, err := cookiejar.New(&options) if err != nil { return nil, err } client := http.Client{Jar: jar} tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client.Transport = tr client.CheckRedirect = nil jClient.httpClient = &client // Provide a no-op logger as the default jClient.Log = log.New(ioutil.Discard, "", log.LstdFlags) return jClient, nil }
func NewClient(host string, User string, Passwd string, httpClient *http.Client) (client *Client, err error) { if httpClient == nil { httpClient = http.DefaultClient } transport := &httpclient.Transport{ ConnectTimeout: 1 * time.Second, ResponseHeaderTimeout: 10 * time.Second, RequestTimeout: 30 * time.Second, } defer transport.Close() httpClient.Transport = transport client = &Client{ client: httpClient, UserAgent: userAgent, apiUser: User, apiPasswd: Passwd, } if err := client.SetHost(host); err != nil { return nil, err } client.Repositories = &RepositoriesService{client: client} client.Tasks = &TasksService{client: client} return }
// TODO(tiborvass): remove authConfig param once registry client v2 is vendored func NewSession(client *http.Client, authConfig *cliconfig.AuthConfig, endpoint *Endpoint) (r *Session, err error) { r = &Session{ authConfig: authConfig, client: client, indexEndpoint: endpoint, } var alwaysSetBasicAuth bool // If we're working with a standalone private registry over HTTPS, send Basic Auth headers // alongside all our requests. if endpoint.VersionString(1) != IndexServerAddress() && endpoint.URL.Scheme == "https" { info, err := endpoint.Ping() if err != nil { return nil, err } if info.Standalone && authConfig != nil { logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String()) alwaysSetBasicAuth = true } } // Annotate the transport unconditionally so that v2 can // properly fallback on v1 when an image is not found. client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth) jar, err := cookiejar.New(nil) if err != nil { return nil, errors.New("cookiejar.New is not supposed to return an error") } client.Jar = jar return r, nil }
// NewClient initializes a new API client for the given host and API version. // It uses the given http client as transport. // It also initializes the custom http headers to add to each request. // // It won't send any version information if the version number is empty. It is // highly recommended that you set a version or your client may break if the // server is upgraded. func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { proto, addr, basePath, err := ParseHost(host) if err != nil { return nil, err } if client == nil { client = &http.Client{} } if client.Transport == nil { // setup the transport, if not already present transport := new(http.Transport) sockets.ConfigureTransport(transport, proto, addr) client.Transport = transport } return &Client{ host: host, proto: proto, addr: addr, basePath: basePath, client: client, version: version, customHTTPHeaders: httpHeaders, }, nil }
func TestTransformingTransport(t *testing.T) { client := new(http.Client) tr := &TransformingTransport{testTransport{}, client} client.Transport = tr tests := []struct { url string code int expectError bool }{ {"http://good.test/png#1", http.StatusOK, false}, {"http://good.test/error#1", http.StatusInternalServerError, true}, // TODO: test more than just status code... verify that image // is actually transformed and returned properly and that // non-image responses are returned as-is } for _, tt := range tests { req, _ := http.NewRequest("GET", tt.url, nil) resp, err := tr.RoundTrip(req) if err != nil { if !tt.expectError { t.Errorf("RoundTrip(%v) returned unexpected error: %v", tt.url, err) } continue } else if tt.expectError { t.Errorf("RoundTrip(%v) did not return expected error", tt.url) } if got, want := resp.StatusCode, tt.code; got != want { t.Errorf("RoundTrip(%v) returned status code %d, want %d", tt.url, got, want) } } }
// WithContext returns a new context in a similar way NewContext does, // but initiates the new context with the specified parent. func WithContext(parent context.Context, projID string, c *http.Client) context.Context { // TODO(bradfitz): delete internal.Transport. It's too wrappy for what it does. // Do User-Agent some other way. if _, ok := c.Transport.(*internal.Transport); !ok { c.Transport = &internal.Transport{Base: c.Transport} } return internal.WithContext(parent, projID, c) }
func NewReplayerClient(r io.Reader) (http.Client, error) { client := http.Client{} transport, err := NewReplayerTransport(r) if err != nil { return client, err } client.Transport = transport return client, err }
func NewWithClient(client *http.Client) *Recorder { r := &Recorder{Client: client} r.originalTransport = client.Transport if r.originalTransport == nil { r.originalTransport = &http.Transport{} } client.Transport = &roundTripRecorder{RoundTripper: r.originalTransport} return r }
// Returns the http.Client's TLS Config, traversing and generating any // defaults along the way to get it. func ClientTLSConfig(cl *http.Client) *tls.Config { if cl.Transport == nil { cl.Transport = http.DefaultTransport } tr := cl.Transport.(*http.Transport) if tr.TLSClientConfig == nil { tr.TLSClientConfig = &tls.Config{} } return tr.TLSClientConfig }
// ActivateNonDefault starts the mock environment with a non-default http.Client. // This emulates the Activate function, but allows for custom clients that do not use // http.DefaultTransport // // To enable mocks for a test using a custom client, activate at the beginning of a test: // client := &http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 60 * time.Second}} // httpmock.ActivateNonDefault(client) func ActivateNonDefault(client *http.Client) { if Disabled() { return } // save the custom client & it's RoundTripper oldTransport = client.Transport oldClient = client client.Transport = DefaultTransport }
func NewClient(login *Login, insecure bool) *Client { c := http.Client{} if tr := getTransportConfig(insecure); tr != nil { c.Transport = tr } return &Client{ client: c, login: login, } }
func SpawnMessageFetcher(addr, topic, group string) *MessageFetcher { useUnixDomainSocket := false var baseURL string if strings.HasPrefix(addr, "/") { fmt.Printf("Using UDS client for %s\n", addr) baseURL = "http://_" useUnixDomainSocket = true } else { fmt.Printf("Using net client for %s\n", addr) baseURL = fmt.Sprintf("http://%s", addr) } url := fmt.Sprintf("%s/topics/%s/messages?group=%s", baseURL, topic, group) var httpClt http.Client if useUnixDomainSocket { dial := func(proto, ignoredAddr string) (net.Conn, error) { return net.Dial("unix", addr) } httpClt.Transport = &http.Transport{Dial: dial} } mf := &MessageFetcher{ url: url, httpClt: httpClt, messages: make(chan []byte), closingCh: make(chan struct{}), } mf.wg.Add(1) go func() { defer mf.wg.Done() for { message, err := mf.fetchMessage() if err != nil { fmt.Printf("Failed to fetch a message: err=(%s)\n", err) select { case <-mf.closingCh: return case <-time.After(backOffTimeout): } continue } if message != nil { mf.messages <- message } select { case <-mf.closingCh: return default: } } }() return mf }
//返回一个可设置代理的 http Client,代理在全局变量 proxy 中设定 func Proxy() *http.Client { var conn http.Client if proxy != "" { proxyUrl, err := url.Parse(proxy) if err != nil { fmt.Println(err) os.Exit(2) } conn.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)} } return &conn }
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/log/9429c03e-a07a-48ef-8a74-a4c2ace992a2" 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) } // bytes, err := ioutil.ReadAll(resp.Body) // if err != nil { // panic(err) // } //temp := resp.Header["Content-Disposition"] //temp2 := string.Fields("[attachment; filename=") //temp2 := strings.Trim(temp, "[attachment; filename=") //fmt.Println(temp2) //fmt.Println(bytes) //var result map[string]interface{} //err = json.Unmarshal(bytes, &result) //if err != nil { // panic(err) // } // fmt.Println(result) /* defer resp.Body.Close() out, err := os.Create("filename.tar.gz") if err != nil { panic(err) } defer out.Close() io.Copy(out, resp.Body) fmt.Println(out) */ }
// NewHTTPLogger creates an HTTPLogger by inspecting the connection's Read // method of an http.Client. func NewHTTPLogger(client *http.Client) *HTTPLogger { httpLogger := &HTTPLogger{ client: client, startTime: time.Now(), avgByteCounter: newAvgCounter()} if client.Transport == nil { client.Transport = &http.Transport{} } if transport, ok := client.Transport.(*http.Transport); ok { transport.Dial = httpLogger.wrappedDial } return httpLogger }
// WithContext returns a new context in a similar way NewContext does, // but initiates the new context with the specified parent. func WithContext(parent context.Context, projID string, c *http.Client) context.Context { // TODO(bradfitz): delete internal.Transport. It's too wrappy for what it does. // Do User-Agent some other way. if c == nil { panic("invalid nil *http.Client passed to WithContext") } if _, ok := c.Transport.(*internal.Transport); !ok { base := c.Transport if base == nil { base = http.DefaultTransport } c.Transport = &internal.Transport{Base: base} } return internal.WithContext(parent, projID, c) }
func newHttpTransporter() (trans *httpTransporter) { tr := new(http.Transport) tr.DisableCompression = true tr.DisableKeepAlives = false tr.MaxIdleConnsPerHost = 4 jar := cookieJar if DisableGlobalCookie { jar, _ = cookiejar.New(nil) } client := new(http.Client) client.Jar = jar client.Transport = tr trans = new(httpTransporter) trans.Client = client trans.Header = new(http.Header) return }
func TestRetryTimeout(t *testing.T) { d := time.Millisecond rt := &fixedRoundTripper{failUntil: time.Now().Add(d)} c := http.Client{} c.Transport = retry.Retry(retry.MaxAttempts(0), retry.Timeout(2*d), retry.Next(rt)) resp, err := c.Get("http://bar") if err != nil { t.Fatal(err) } if want, have := http.StatusTeapot, resp.StatusCode; want != have { t.Fatalf("want %v, have %v", want, have) } t.Logf("just FYI, it took %d attempt(s) to succeed", rt.count) }
func TestRetryMaxAttempts(t *testing.T) { rt := &fixedRoundTripper{failFor: 2} c := http.Client{} c.Transport = retry.Retry(retry.MaxAttempts(3), retry.Next(rt)) resp, err := c.Get("http://foo") if err != nil { t.Fatal(err) } if want, have := http.StatusTeapot, resp.StatusCode; want != have { t.Fatalf("want %v, have %v", want, have) } if want, have := 3, rt.count; want != have { t.Errorf("want %v, have %v", want, have) } }
// NewDocument is a Document constructor that takes a string URL as argument. // You can also add a string proxy after this URL. If you have no proxy, add // nothing. If you set more than two arguments, it use the second as a proxy. // It loads the specified document, parses it, and stores the root Document // node, ready to be manipulated. func NewDocument(URL string, proxy ...string) (*Document, error) { var conn *http.Client = http.DefaultClient //Generate a proxy if len(proxy) != 0 && proxy[0] != "" { proxyUrl, e := url.Parse(proxy[0]) if e != nil { return nil, e } conn.Transport = &http.Transport{ Proxy: http.ProxyURL(proxyUrl), } } // Load the URL res, e := conn.Get(URL) if e != nil { return nil, e } return NewDocumentFromResponse(res) }
func (p *Proxy) Test(client *http.Client, URL string) error { transport, err := p.Transport() if err != nil { return err } client.Transport = transport req, err := http.NewRequest("GET", URL, nil) if err != nil { return err } req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36") resp, err := client.Do(req) if err != nil { return err } io.Copy(os.Stdout, resp.Body) fmt.Println("") return nil }
// NewClient creates and returns a client that will send requests to host, using the // http.Client httpCli with transport and httpHeaders. func NewClient(host string, transport *http.Transport) (*Client, error) { var ( httpCli *http.Client protoAddrParts = strings.SplitN(host, "://", 2) proto, addr string ) if len(protoAddrParts) != 2 { return nil, fmt.Errorf("invalid host format '%s'", host) } else { proto, addr = protoAddrParts[0], protoAddrParts[1] } switch proto { case "tcp": if _, err := url.Parse("tcp://" + addr); err != nil { return nil, err } addr = "http://" + addr case "http": addr = "http://" + addr } transport = configureTransport(transport, proto, addr) if httpCli != nil { httpCli.Transport = transport } else { httpCli = &http.Client{Transport: transport} } r := resty.New().SetTransport(transport).SetScheme("http").SetCloseConnection(true) if proto != "unix" { r.SetHostURL(addr) } log.Debugf("Client talking with host: %s", host) return &Client{ r, }, nil }
// NewContextWithOptions creates a new Context instance. // ipAddress is the private ip address of the hue bridge, but could be a // DNS name. // userId is the user Id / developer Id (See hue documentation). // options contains optional settings for the created context. func NewContextWithOptions( ipAddress, userId string, options *Options) *Context { if options == nil { options = kDefaultOptions } allUrl := &url.URL{ Scheme: "http", Host: ipAddress, Path: fmt.Sprintf("/api/%s/groups/0/action", userId), } var client http.Client if options.Timeout > 0 { client.Transport = &http.Transport{Dial: timeoutDialer(options.Timeout)} } return &Context{ ipAddress: ipAddress, userId: userId, allUrl: allUrl, client: &client} }
// NewProxy constructs a new proxy. The provided http RoundTripper will be // used to fetch remote URLs. If nil is provided, http.DefaultTransport will // be used. func NewProxy(transport http.RoundTripper, cache Cache) *Proxy { if transport == nil { transport = http.DefaultTransport } if cache == nil { cache = NopCache } client := new(http.Client) client.Transport = &httpcache.Transport{ Transport: &TransformingTransport{transport, client}, Cache: cache, MarkCachedResponses: true, } return &Proxy{ Client: client, Cache: cache, } }