Table of Contents
Question content
Solution
Home Backend Development Golang How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake

How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake

Feb 11, 2024 am 10:18 AM

如何修复 proxyconnect tcp: tls: 第一条记录看起来不像 TLS 握手

php editor Apple is here to bring you a solution to the "proxyconnect tcp: tls: first record does not look like TLS handshake" problem. This error usually occurs when using a proxy server and can cause network connection issues. Before we can solve this problem, we first need to understand the source of the problem. With the following simple steps, we'll show you how to fix this problem to ensure your network connection is functioning properly.

Question content

In How to use the REST API in Go, a fully working example code is provided to call the public REST API. But if I try the example I get this error:

error getting cat fact: 
      Get "https://catfact.ninja/fact": 
      proxyconnect tcp: tls: first record does not look like a TLS handshake
Copy after login

Documentation on http status

<code>
For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:
</code>
Copy after login

And transfer documents:

<code>    // DialContext specifies the dial function for creating unencrypted TCP connections.
    // If DialContext is nil (and the deprecated Dial below is also nil),
    // then the transport dials using package net.
    //
    // DialContext runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later DialContext completes.
    DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
</code>
Copy after login

So I'm assuming that I have to configure the Dialcontext to enable insecure connections from the client to the proxy without TLS. But I don't know how to do it. Read these:

  • How to do proxy and TLS in golang;
  • How to do HTTP/HTTPS GET through a proxy; and
  • How to perform https request with wrong certificate?

doesn't help either. Some have the same error proxyconnect tcp: tls:first record does not Look like a TLS handshake and explain why:

<code>
This is because the proxy answers with an plain HTTP error to the strange HTTP request (which is actually the start of the TLS handshake).
</code>
Copy after login

But Steffen's reply does not have sample code on how to set itDialContext func(ctx context.Context, network, addr string), Bogdan and cyberdelia both recommend setting tls.Config{InsecureSkipVerify: true}, for example < /p>

<code>    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
</code>
Copy after login

But the above has no effect. I still get the same error. And the connection still calls https://* instead of http://*

Here is sample code where I tried to include the above suggestions and adapt them:

<code>var tr = &http.Transport{ TLSClientConfig: 
                           &tls.Config{InsecureSkipVerify: true}, } 
                           // lacks DialContext config
var client*  http.Client = &http.Client{Transport: tr} // modified * added
// var client *http.Client // code from tutorial

type CatFact struct {
    Fact   string `json:"fact"`
    Length int    `json:"length"`
}

func GetCatFact() {
    url := "http://catfact.ninja/fact" // changed from https to http
    var catFact CatFact

    err := GetJson(url, &catFact)
    if err != nil {
        fmt.Printf("error getting cat fact: %s\n", err.Error())
    } else {
        fmt.Printf("A super interesting Cat Fact: %s\n", catFact.Fact)
    }
}

func main() {
    client = &http.Client{Timeout: 10 * time.Second}
    GetCatFact()
    // same error 
    // proxyconnect tcp: tls: first record does 
    //                   not look like a TLS handshake
    // still uses https 
    // for GET catfact.ninja
}
</code>
Copy after login

How do I configure the connection to use an unencrypted connection from myClient through a proxy to the server? Would setting DialContext func(ctx context.Context, network, addr string) help to do this? what to do?

Solution

I just tried:

package main

import (
    "context"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "net"
    "net/http"
    "time"
)

type CatFact struct {
    Fact   string `json:"fact"`
    Length int    `json:"length"`
}

// Custom dialing function to handle connections
func customDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
    conn, err := net.Dial(network, addr)
    return conn, err
}

// Function to get a cat fact
func GetCatFact(client *http.Client) {
    url := "https://catfact.ninja/fact"  // Reverted back to https
    var catFact CatFact

    err := GetJson(url, &catFact, client)
    if err != nil {
        fmt.Printf("error getting cat fact: %s\n", err.Error())
    } else {
        fmt.Printf("A super interesting Cat Fact: %s\n", catFact.Fact)
    }
}

// Function to send a GET request and decode the JSON response
func GetJson(url string, target interface{}, client *http.Client) error {
    resp, err := client.Get(url)
    if err != nil {
        return fmt.Errorf("error sending GET request: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("received non-OK HTTP status: %d", resp.StatusCode)
    }

    err = json.NewDecoder(resp.Body).Decode(target)
    if err != nil {
        return fmt.Errorf("error decoding JSON response: %w", err)
    }

    return nil
}

func main() {
    // Create a custom Transport with the desired settings
    tr := &http.Transport{
        Proxy: http.ProxyFromEnvironment,  // Use the proxy settings from the environment
        DialContext: customDialContext,    // Use the custom dialing function
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,  // Skip certificate verification (not recommended in production)
        },
    }

    // Create a new HTTP client using the custom Transport
    client := &http.Client{
        Transport: tr,
        Timeout:   10 * time.Second,
    }

    // Call the function to get a cat fact
    GetCatFact(client)
}
Copy after login

it includes:

  • Custom dialing functioncustomDialContext
    This function is currently a simple wrapper around net.Dial, but it provides a place to introduce custom dialing logic if necessary. It is used as a custom dialing function for creating network connections.

  • Transmission configuration:

    • The modified code configures a custom http.Transport with specific settings, including custom dialing functionality, proxy settings in the environment, and a TLS configuration that skips certificate verification (for testing).
    • The original code also attempts to configure a custom http.Transport, but only contains a TLS configuration that skips certificate verification, and does not set custom dial-up capabilities or proxy settings.
  • Client configuration:

    • The modified code uses a custom http.Transport to create a new http.Client and sets the timeout to 10 seconds.
    • The original code also tries to create a new http.Client with a custom http.Transport, but then in the main function, it uses the new http.Client overrides the client variable, which contains the default Transport and a timeout of 10 seconds, effectively discarding the custom Transport.
  • Function signature:

    • The modified code modifies the GetCatFact and GetJson functions to accept the *http.Client parameter, allowing them to be used in main Custom http.Client created in.
    • The original code does not pass http.Client to these functions, so they will use the default http.Client provided by the net/http package.
  • Website:

    • The modified code restores the URL in the GetCatFact function to "https://catfact.ninja/fact" since the server redirects HTTP requests to HTTPS anyway.
    • The original code has changed the URL to "http://catfact.ninja/fact" to avoid TLS handshake errors.
<小时/>

The customDialContext function in the code provided above does not contain any logic to specifically ignore TLS handshake errors or change the TLS handshake to a non-TLS connection. It only provides custom dialing function. In the provided form, net.Dial is called directly without any special processing.

The mechanism for ignoring TLS certificate verification errors is actually provided by the TLSClientConfig field of the http.Transport structure, specifically by setting the InsecureSkipVerify field to true

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
Copy after login

该配置告诉 Go 跳过验证服务器的证书链和主机名,这是 TLS 握手过程的一部分。但是,它不会忽略其他类型的 TLS 握手错误或切换到非 TLS 连接。通常不建议在生产环境中使用 InsecureSkipVerify: true,因为它会禁用重要的安全检查。

如果您想强制使用非 TLS(纯 HTTP)连接,通常只需使用 http:// URL,而不是 https:// URL。但是,如果服务器或代理服务器将 HTTP 重定向到 HTTPS(例如 http://catfact.ninja/fact 的情况),则客户端将遵循重定向并切换到 TLS 连接。

The above is the detailed content of How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles