Golang中如何在net/http处理器中使用tls.ClientHelloInfo

Golang中如何在net/http处理器中使用tls.ClientHelloInfo 你好!我需要在 net/http 处理程序中获取 ClientHelloInfo,请问如何获取?<3

9 回复

能给我看个例子吗?

更多关于Golang中如何在net/http处理器中使用tls.ClientHelloInfo的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我试过了,没有用 ;(

你能展示一下你目前尝试过的内容吗?

我需要在 net/http 的 handlefunc 中获取 tls.ClientHelloInfo。

你能说得更具体一点吗?

你是什么意思?

现在清楚了,

你到目前为止尝试了什么?

你可以查看 tls.Config.GetCertificate;你可以自定义该函数并访问 ClientHelloInfo

func main() {
    fmt.Println("hello world")
}

我从未直接做过,但这个帖子讨论过类似的内容。

类似的内容也可以在这里找到。

问题是,你在处理程序中需要什么;为什么需要访问 ClientHelloInfo?你不能使用 Request.TLS 吗?

在 net/http 处理程序中获取 tls.ClientHelloInfo,可以通过自定义 tls.ConfigGetConfigForClient 回调函数来实现。以下是一个示例代码:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
)

func main() {
    // 创建自定义的 TLS 配置
    tlsConfig := &tls.Config{
        GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
            // 在这里可以访问 ClientHelloInfo
            fmt.Printf("Client SNI: %s\n", hello.ServerName)
            fmt.Printf("Client Cipher Suites: %v\n", hello.CipherSuites)
            fmt.Printf("Client Supported Versions: %v\n", hello.SupportedVersions)
            
            // 返回默认配置或自定义配置
            return &tls.Config{
                Certificates: []tls.Certificate{yourCertificate}, // 替换为你的证书
                MinVersion:   tls.VersionTLS12,
            }, nil
        },
    }

    // 创建 HTTP 服务器
    server := &http.Server{
        Addr:      ":8443",
        TLSConfig: tlsConfig,
        Handler:   http.HandlerFunc(yourHandler), // 替换为你的处理器
    }

    // 启动 HTTPS 服务器
    server.ListenAndServeTLS("cert.pem", "key.pem") // 替换为你的证书文件路径
}

func yourHandler(w http.ResponseWriter, r *http.Request) {
    // 注意:处理器内部无法直接访问 ClientHelloInfo
    // 需要通过其他方式传递(如上下文)
    w.Write([]byte("Hello, TLS!"))
}

如果需要将 ClientHelloInfo 传递给处理器,可以通过请求上下文传递:

// 自定义类型用于存储 ClientHelloInfo
type clientHelloKey struct{}

// 在 GetConfigForClient 中存储信息
GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
    // 创建新配置并存储回调函数
    return &tls.Config{
        Certificates: []tls.Certificate{yourCertificate},
        MinVersion:   tls.VersionTLS12,
        GetCertificate: func(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
            // 将 ClientHelloInfo 存储到连接状态
            chi.Conn.SetContext(context.WithValue(chi.Conn.Context(), clientHelloKey{}, hello))
            return &yourCertificate, nil
        },
    }, nil
}

// 在处理器中获取信息
func yourHandler(w http.ResponseWriter, r *http.Request) {
    if tlsConn, ok := r.TLS.(*tls.Conn); ok {
        if chi, ok := tlsConn.Context().Value(clientHelloKey{}).(*tls.ClientHelloInfo); ok {
            fmt.Printf("Handler got SNI: %s\n", chi.ServerName)
        }
    }
    w.Write([]byte("Hello with ClientHelloInfo!"))
}

注意:GetConfigForClient 在 TLS 握手期间调用,此时 HTTP 请求尚未形成。因此,必须通过连接上下文将信息传递给后续的处理器。

回到顶部