给定常量值的名称 [英] Name of a constant given its value
问题描述
如何根据给定的值获取常量的名称?
How do you get the name of a constant given its value ?
更具体地说(为了获得更易理解的理解),我正在使用 crypto/tls
包.密码套件定义为常量:
More specifically (and to get a more readable understanding), I'm working with the crypto/tls
package. Cipher suites are defined as constants:
const (
TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a
TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f
TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014
)
与服务器成功握手后,我可以通过连接到达商定的Ciphersuite:
After a successful handshake with a server, I can get to the Ciphersuite agreed on through the connection:
c, _ := tls.Dial("tcp", "somedomain.com:443", nil)
// Suppose everything went right
// This is the Ciphersuite for the conn:
cipher := c.ConnectionState().Ciphersuite
密码
这是一个uint16.有没有办法将其显示为字符串,例如 TLS_RSA_WITH_3DES_EDE_CBC_SHA
?
cipher
here is an uint16. Is there a way to display it as a string, for instance TLS_RSA_WITH_3DES_EDE_CBC_SHA
if that's what was agreed upon ?
推荐答案
恐怕不可能.
常量在编译时解析,并且 reflect
包中没有任何内容可让您检索名称.
I am afraid that is not possible.
The constants are resolved at compile time and there is nothing in the reflect
package that allows you to retrieve the name.
我建议使用以下名称创建地图:
What I suggest is creating a map with the names:
var constLookup = map[uint16]string{
tls.TLS_RSA_WITH_RC4_128_SHA: `TLS_RSA_WITH_RC4_128_SHA`,
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: `TLS_RSA_WITH_3DES_EDE_CBC_SHA`,
...
}
这篇关于给定常量值的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!