How to consume a REST API in Go中,提供了fully working example code来调用公共REST API.但是,如果我try 该示例,则会出现以下错误:

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

documentation about http个州

要控制代理、TLS配置、保持连接、压缩和其他设置,请创建传输:

Transport documentation名开始:

    // 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)

因此,我假设我必须配置拨号上下文以启用从我的客户端到代理的不安全连接without TLS.但我不知道该怎么做.阅读这些内容:

也没有起到任何作用.一些人有相同的错误proxyconnect tcp: tls: first record does not look like a TLS handshake并解释了原因:

这是因为代理对奇怪的HTTP请求(实际上是TLS握手的开始)的响应是一个简单的HTTP错误.

但是Steffen's reply没有示例代码如何设置DialContext func(ctx context.Context, network, addr string),Bogdancyberdelia都建议这样设置tls.Config{InsecureSkipVerify: true}

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

但上述措施并未奏效.我仍然收到相同的错误.而且连接仍在呼叫https://*,而不是http://*

这是样例代码,我try 包含上述建议并对其进行修改:

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
}

如何将连接配置为使用从myClient通过代理到服务器的未加密连接?设定DialContext func(ctx context.Context, network, addr string)会有助于做到这一点吗?如何做到这一点呢?

推荐答案

我刚试过了:

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)
}

它包括:

  • A custom dialing function customDialContext:
    That function is currently a simple wrapper around net.Dial, but it provides a place where custom dialing logic could be introduced if necessary. It serves as a custom dialing function that is used to create network connections.

  • Transport configuration:

    • 修改后的代码使用特定设置配置自定义http.Transport,包括自定义拨号功能、来自环境的代理设置以及跳过证书验证(用于测试)的TLS配置.
    • 原始代码还试图配置自定义http.Transport,但它只包括跳过证书验证的TLS配置,并且没有设置自定义拨号功能或代理设置.
  • Client configuration:

    • 修改后的代码使用自定义http.Transport创建一个新的http.Client,并将超时设置为10秒.
    • 原始代码还试图使用自定义http.Transport创建一个新的http.Client,但后来在main函数中,它用具有默认Transport和超时10秒的新http.Client覆盖了client变量,从而有效地丢弃了自定义Transport.
  • Function signatures:

    • 修改后的代码修改了GetCatFactGetJson函数以接受*http.Client参数,允许它们使用在main中创建的自定义http.Client.
    • 原始代码没有将http.Client传递给这些函数,因此它们将使用net/http包提供的默认http.Client.
  • URL:

    • 修改后的代码将url恢复为"GetCatFact函数中的https://catfact.ninja/fact",因为服务器无论如何都会将HTTPS请求重定向到HTTPS.
    • 原始代码将url更改为"http://catfact.ninja/fact"",以避免TLS握手错误.

Go相关问答推荐

gorm如何声明未自动更新的unix时间戳米尔斯字段

为什么(编码器).EncodeElement忽略";,innerxml";标记?

Golang中的泛型 struct /接口列表

Docker Compose Health Check未退出,错误为无法启动

什么东西逃到了堆里?

提供的client_secret与此帐户上任何关联的SetupIntent都不匹配

如何忽略打印达到最大深度限制 go colly

错误!在为 age-viewer-go 运行 wails dev 或 wails build 命令时

Go struct 匿名字段是公开的还是私有的?

使用 LINQ 对内部数组进行排序

Apache Beam 在 Go 中从 PCollection 中 Select 前 N 行

如何在模板中传递和访问 struct 片段和 struct

如何使用 Docker 引擎 SDK 和 Golang 运行 docker 挂载卷

如何模仿联合类型

如何在 GORM 中迭代一个 int 数组

Go AST:获取所有 struct

为什么 go.mod 中的所有依赖都是间接的?

测试包外文件时的 Golang 测试覆盖率

正则表达式处理数字签名的多个条目

为什么在 goroutine 中声明时,benbjohnson/clock 模拟计时器不执行?