常量块中的原始字符串文字

时间:2018-11-29 12:33:31

标签: string go const string-literals

我正在测试x509 Certificate Verify example,并且此功能(根据示例)有效:

const rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
. . .
yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
-----END CERTIFICATE-----`

const certPEM = `
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
. . .
yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
-----END CERTIFICATE-----`

但这不是:

const (
    rootPEM = `
    -----BEGIN CERTIFICATE-----
    MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
    . . .
    yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
    -----END CERTIFICATE-----`

    certPEM = `
    -----BEGIN CERTIFICATE-----
    MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
    . . .
    yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
    -----END CERTIFICATE-----`
)

使用恒定块/组时会有什么变化? (就本例而言,使用常量块时,它在panic: failed to parse root certificate处失败)

1 个答案:

答案 0 :(得分:4)

“没有任何变化”,只是对分组的变体进行了缩进,这意味着原始字符串文字的所有行都以制表符或空格开头,证书解析器可能会冒犯这些空格。

像这样尝试:

const (
    rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
. . .
yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
-----END CERTIFICATE-----`

    certPEM = `
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
. . .
yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
-----END CERTIFICATE-----`
)

(注意:原始字符串文字的多行不缩进。)