本文整理汇总了Golang中net/http/httputil.NewClientConn函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClientConn函数的具体用法?Golang NewClientConn怎么用?Golang NewClientConn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClientConn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeHTTP
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req1, req2 := DuplicateRequest(req)
go func() {
defer func() {
if r := recover(); r != nil && *debug {
fmt.Println("Recovered in f", r)
}
}()
client_tcp_conn, _ := net.DialTimeout("tcp", h.Alternative, time.Duration(1*time.Second)) // Open new TCP connection to the server
client_http_conn := httputil.NewClientConn(client_tcp_conn, nil) // Start a new HTTP connection on it
client_http_conn.Write(req1) // Pass on the request
client_http_conn.Read(req1) // Read back the reply
client_http_conn.Close() // Close the connection to the server
}()
defer func() {
if r := recover(); r != nil && *debug {
fmt.Println("Recovered in f", r)
}
}()
client_tcp_conn, _ := net.DialTimeout("tcp", h.Target, time.Duration(3*time.Second)) // Open new TCP connection to the server
client_http_conn := httputil.NewClientConn(client_tcp_conn, nil) // Start a new HTTP connection on it
client_http_conn.Write(req2) // Pass on the request
resp, _ := client_http_conn.Read(req2) // Read back the reply
resp.Write(w) // Write the reply to the original connection
client_http_conn.Close() // Close the connection to the server
}
示例2: ServeHTTP
// ServeHTTP duplicates the incoming request (req) and does the request to the Target and the Alternate target discading the Alternate response
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req1, req2 := DuplicateRequest(req)
go func() {
defer func() {
if r := recover(); r != nil && *debug {
fmt.Println("Recovered in f", r)
}
}()
// Open new TCP connection to the server
clientTcpConn, err := net.DialTimeout("tcp", h.Alternative, time.Duration(time.Duration(*alternateTimeout)*time.Second))
if err != nil {
if *debug {
fmt.Printf("Failed to connect to %s\n", h.Alternative)
}
return
}
clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
defer clientHttpConn.Close() // Close the connection to the server
err = clientHttpConn.Write(req1) // Pass on the request
if err != nil {
if *debug {
fmt.Printf("Failed to send to %s: %v\n", h.Alternative, err)
}
return
}
_, err = clientHttpConn.Read(req1) // Read back the reply
if err != nil {
if *debug {
fmt.Printf("Failed to receive from %s: %v\n", h.Alternative, err)
}
return
}
}()
defer func() {
if r := recover(); r != nil && *debug {
fmt.Println("Recovered in f", r)
}
}()
// Open new TCP connection to the server
clientTcpConn, err := net.DialTimeout("tcp", h.Target, time.Duration(time.Duration(*productionTimeout)*time.Second))
if err != nil {
fmt.Printf("Failed to connect to %s\n", h.Target)
return
}
clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
defer clientHttpConn.Close() // Close the connection to the server
err = clientHttpConn.Write(req2) // Pass on the request
if err != nil {
fmt.Printf("Failed to send to %s: %v\n", h.Target, err)
return
}
resp, err := clientHttpConn.Read(req2) // Read back the reply
if err != nil {
fmt.Printf("Failed to receive from %s: %v\n", h.Target, err)
return
}
resp.Write(w) // Write the reply to the original connection
}
示例3: connectToRunServer
func (ctx *runContext) connectToRunServer() (*http.Response, net.Conn, error) {
if ctx.attachURL == "" {
return nil, nil, errgo.New("No attach URL to connect to")
}
req, err := http.NewRequest("CONNECT", ctx.attachURL, nil)
if err != nil {
return nil, nil, errgo.Mask(err, errgo.Any)
}
req.SetBasicAuth("", config.AuthenticatedUser.AuthenticationToken)
url, err := url.Parse(ctx.attachURL)
if err != nil {
return nil, nil, errgo.Mask(err, errgo.Any)
}
dial, err := net.Dial("tcp", url.Host)
if err != nil {
return nil, nil, errgo.Mask(err, errgo.Any)
}
var conn *httputil.ClientConn
if url.Scheme == "https" {
host := strings.Split(url.Host, ":")[0]
config := *config.TlsConfig
config.ServerName = host
tls_conn := tls.Client(dial, &config)
conn = httputil.NewClientConn(tls_conn, nil)
} else if url.Scheme == "http" {
conn = httputil.NewClientConn(dial, nil)
} else {
return nil, nil, errgo.Newf("Invalid scheme format %s", url.Scheme)
}
res, err := conn.Do(req)
if err != httputil.ErrPersistEOF && err != nil {
if err, ok := err.(*net.OpError); ok {
if err.Err.Error() == "record overflow" {
return nil, nil, errgo.Newf(
"Fail to create a secure connection to Scalingo server\n"+
"The encountered error is: %v (ID: CLI-1001)\n"+
"Your firewall or proxy may block the connection to %s",
err, url.Host,
)
}
}
return nil, nil, errgo.Mask(err, errgo.Any)
}
connection, _ := conn.Hijack()
return res, connection, nil
}
示例4: dial
func dial(host string) (conn *httputil.ClientConn) {
var tcp net.Conn
var err error
fmt.Fprintf(os.Stderr, "http-gonsole: establishing a TCP connection ...\n")
proxy := os.Getenv("HTTP_PROXY")
if strings.Split(host, ":")[0] != "localhost" && len(proxy) > 0 {
proxy_url, _ := url.Parse(proxy)
tcp, err = net.Dial("tcp", proxy_url.Host)
} else {
tcp, err = net.Dial("tcp", host)
}
if err != nil {
fmt.Fprintln(os.Stderr, "http-gonsole:", err)
os.Exit(1)
}
if *useSSL {
if len(proxy) > 0 {
connReq := &http.Request{
Method: "CONNECT",
URL: &url.URL{Path: host},
Host: host,
Header: make(http.Header),
}
connReq.Write(tcp)
resp, err := http.ReadResponse(bufio.NewReader(tcp), connReq)
if resp.StatusCode != 200 {
fmt.Fprintln(os.Stderr, "http-gonsole:", resp.Status)
os.Exit(1)
}
if err != nil {
fmt.Fprintln(os.Stderr, "http-gonsole:", err)
os.Exit(1)
}
tcp = tls.Client(tcp, nil)
conn = httputil.NewClientConn(tcp, nil)
} else {
tcp = tls.Client(tcp, nil)
conn = httputil.NewClientConn(tcp, nil)
}
if err = tcp.(*tls.Conn).Handshake(); err != nil {
fmt.Fprintln(os.Stderr, "http-gonsole:", err)
os.Exit(1)
}
if err = tcp.(*tls.Conn).VerifyHostname(strings.Split(host, ":")[0]); err != nil {
fmt.Fprintln(os.Stderr, "http-gonsole:", err)
os.Exit(1)
}
} else {
conn = httputil.NewClientConn(tcp, nil)
}
return
}
示例5: Connect
func Connect(nurl *url.URL) {
req := http.Request{
Method: "GET",
Header: http.Header{},
URL: nurl,
}
dial, err := net.Dial("tcp", nurl.Host)
if err != nil {
fmt.Println(err)
return
}
clientconn := httputil.NewClientConn(dial, nil)
clientconn.Do(&req)
defer clientconn.Close()
rwc, _ := clientconn.Hijack()
defer rwc.Close()
/*
go func(rwc io.ReadWriteCloser) {
bufRead(rwc)
}(rwc)
bufWrite(rwc)
*/
count := 0
for {
count++
fmt.Println(count)
time.Sleep(10 * time.Second)
}
time.Sleep(5 * time.Second)
}
示例6: test_conn
func test_conn(conn *tls.Conn, options *ScanOptions, record *ScanRecord) bool {
//check SSL certificate
success := false
for _, cert := range conn.ConnectionState().PeerCertificates {
for _, verifyHost := range options.Config.ScanGoogleIP.SSLCertVerifyHosts {
if cert.VerifyHostname(verifyHost) != nil {
return false
} else {
success = true
}
}
if success {
break
}
}
for _, verifyHost := range options.Config.ScanGoogleIP.HTTPVerifyHosts {
conn.SetReadDeadline(time.Now().Add(record.httpVerifyTimeout))
req, _ := http.NewRequest("HEAD", "https://"+verifyHost, nil)
res, err := httputil.NewClientConn(conn, nil).Do(req)
if nil != err || res.StatusCode >= 400 {
return false
}
}
return true
}
示例7: sockRequest
func sockRequest(method, endpoint string) ([]byte, error) {
// FIX: the path to sock should not be hardcoded
sock := filepath.Join("/", "var", "run", "docker.sock")
c, err := net.DialTimeout("unix", sock, time.Duration(10*time.Second))
if err != nil {
return nil, fmt.Errorf("could not dial docker sock at %s: %v", sock, err)
}
client := httputil.NewClientConn(c, nil)
defer client.Close()
req, err := http.NewRequest(method, endpoint, nil)
req.Header.Set("Content-Type", "application/json")
if err != nil {
return nil, fmt.Errorf("could not create new request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("could not perform request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
}
return ioutil.ReadAll(resp.Body)
}
示例8: TestContainerApiChunkedEncoding
// Regression test for https://github.com/docker/docker/issues/6231
func (s *DockerSuite) TestContainerApiChunkedEncoding(c *check.C) {
// TODO Windows CI: This can be ported
testRequires(c, DaemonIsLinux)
conn, err := sockConn(time.Duration(10*time.Second), "")
c.Assert(err, checker.IsNil)
client := httputil.NewClientConn(conn, nil)
defer client.Close()
config := map[string]interface{}{
"Image": "busybox",
"Cmd": append([]string{"/bin/sh", "-c"}, defaultSleepCommand...),
"OpenStdin": true,
}
b, err := json.Marshal(config)
c.Assert(err, checker.IsNil)
req, err := http.NewRequest("POST", "/containers/create", bytes.NewBuffer(b))
c.Assert(err, checker.IsNil)
req.Header.Set("Content-Type", "application/json")
// This is a cheat to make the http request do chunked encoding
// Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
// https://golang.org/src/pkg/net/http/request.go?s=11980:12172
req.ContentLength = -1
resp, err := client.Do(req)
c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
resp.Body.Close()
c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
}
示例9: NewDockerClient
// Creates a new Docker client using the Docker unix socket.
func NewDockerClient(dockerSocketPath string) (*httputil.ClientConn, error) {
conn, err := net.Dial("unix", dockerSocketPath)
if err != nil {
return nil, err
}
return httputil.NewClientConn(conn, nil), nil
}
示例10: request
func (b *ContainerBackup) request(method, path string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, path, body)
if err != nil {
return nil, err
}
conn, err := net.Dial(b.proto, b.addr)
if err != nil {
return nil, err
}
clientconn := httputil.NewClientConn(conn, nil)
resp, err := clientconn.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
}
return nil, fmt.Errorf("HTTP %s: %s", http.StatusText(resp.StatusCode), body)
}
return resp, nil
}
示例11: sockRequestRaw
func sockRequestRaw(method, endpoint string, data io.Reader, ct string) ([]byte, error) {
c, err := sockConn(time.Duration(10 * time.Second))
if err != nil {
return nil, fmt.Errorf("could not dial docker daemon: %v", err)
}
client := httputil.NewClientConn(c, nil)
defer client.Close()
req, err := http.NewRequest(method, endpoint, data)
if err != nil {
return nil, fmt.Errorf("could not create new request: %v", err)
}
if ct == "" {
ct = "application/json"
}
req.Header.Set("Content-Type", ct)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("could not perform request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
}
return ioutil.ReadAll(resp.Body)
}
示例12: listenToDockerDaemonMessages
func listenToDockerDaemonMessages(ch chan<- DockerDaemonMessage) {
conn, err := net.Dial("tcp", "0.0.0.0:2375")
if err != nil {
log.Fatal(err)
}
clientConn := httputil.NewClientConn(conn, nil)
req, err := http.NewRequest("GET", "/events", nil)
if err != nil {
log.Fatal(err)
}
resp, err := clientConn.Do(req)
if err != nil {
log.Fatal(err)
}
dec := json.NewDecoder(resp.Body)
for {
var m DockerDaemonMessage
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", m.Status, m.Id)
ch <- m
}
}
示例13: ExampleSocks5Client
func ExampleSocks5Client() {
user := ""
password := ""
client, err := NewSocks5Client("tcp", "127.0.0.1:1080", user, password, Direct)
if err != nil {
return
}
conn, err := client.Dial("tcp", "www.google.com:80")
if err != nil {
return
}
httpClient := httputil.NewClientConn(conn, nil)
defer httpClient.Close()
request, err := http.NewRequest("GET", "/", nil)
if err != nil {
return
}
resp, err := httpClient.Do(request)
if err != nil {
return
}
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return
}
println(string(dump))
return
}
示例14: ExampleSocks4Client
func ExampleSocks4Client() {
user := ""
client, err := NewSocks4Client("tcp", "127.0.0.1:1080", user, Direct)
if err != nil {
return
}
addrs, err := net.LookupHost("www.google.com")
if err != nil {
return
}
if len(addrs) == 0 {
return
}
conn, err := client.Dial("tcp", addrs[0]+":80")
if err != nil {
return
}
httpClient := httputil.NewClientConn(conn, nil)
defer httpClient.Close()
request, err := http.NewRequest("GET", "/", nil)
if err != nil {
return
}
resp, err := httpClient.Do(request)
if err != nil {
return
}
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return
}
println(string(dump))
return
}
示例15: commToDaemon
func commToDaemon(method, path string, jsonData []byte) (resp *http.Response, err error) {
//fmt.Println(method, "/api"+path, string(jsonData))
req, err := http.NewRequest(strings.ToUpper(method), "/api"+path, bytes.NewBuffer(jsonData))
if len(User.userName) > 0 {
req.SetBasicAuth(User.userName, User.password)
}
/* else {
req.Header.Set("Authorization", "Basic "+os.Getenv("DAEMON_USER_AUTH_INFO"))
}
*/
conn, err := net.Dial("tcp", CmdHttpServer)
if err != nil {
fmt.Println(err.Error())
fmt.Println("Datahub daemon not running? Use 'datahub --daemon' to start daemon.")
os.Exit(2)
}
//client := &http.Client{}
client := httputil.NewClientConn(conn, nil)
return client.Do(req)
/*
defer resp.Body.Close()
response = *resp
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
*/
}