How do you get the name of a constant given its value ?
More specifically (and to get a more readable understanding), I\'m working with the crypto/tls
packa
Note: As of Go 1.4, the String()
code below can be auto-generated using Go's new generate
feature, combined with the stringer
command. See here for more info.
Apart from ANisus' answer, you can do the following.
package main
import "fmt"
import "crypto/tls"
type Ciphersuite uint16
const (
TLS_RSA_WITH_RC4_128_SHA = Ciphersuite(tls.TLS_RSA_WITH_RC4_128_SHA)
TLS_RSA_WITH_3DES_EDE_CBC_SHA = Ciphersuite(tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA)
TLS_RSA_WITH_AES_128_CBC_SHA = Ciphersuite(tls.TLS_RSA_WITH_AES_128_CBC_SHA)
TLS_RSA_WITH_AES_256_CBC_SHA = Ciphersuite(tls.TLS_RSA_WITH_AES_256_CBC_SHA)
TLS_ECDHE_RSA_WITH_RC4_128_SHA = Ciphersuite(tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA)
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = Ciphersuite(tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA)
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = Ciphersuite(tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA)
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = Ciphersuite(tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA)
)
func (cs Ciphersuite) String() string {
switch cs {
case TLS_RSA_WITH_RC4_128_SHA:
return "TLS_RSA_WITH_RC4_128_SHA"
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"
case TLS_RSA_WITH_AES_128_CBC_SHA:
return "TLS_RSA_WITH_AES_128_CBC_SHA"
case TLS_RSA_WITH_AES_256_CBC_SHA:
return "TLS_RSA_WITH_AES_256_CBC_SHA"
case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
return "TLS_ECDHE_RSA_WITH_RC4_128_SHA"
case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
}
return "Unknown"
}
func main() {
cs := TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
fmt.Printf("0x%04x = %s\n", uint16(cs), cs)
cs = TLS_RSA_WITH_RC4_128_SHA
fmt.Printf("0x%04x = %s\n", uint16(cs), cs)
cs = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
fmt.Printf("0x%04x = %s\n", uint16(cs), cs)
}
You can test it on the go playground.