我在 Go 中有以下字符串 blob:
AWS_FIREHOSE_US_WEST_2_ENDPOINT: https://foobar.firehose.us-west-2.amazonaws.com
BOT_NAME: mybot
DEV_MODE: false
GITHUB_APP_ID: 1234
GITHUB_INSTALLATION_ID: 1234
GITHUB_ORG_NAME: myorg
SERVICE_WHO_IS_WHO_DEFAULT_HOST: foo.bar
SERVICE_WHO_IS_WHO_DEFAULT_PORT: 80
SERVICE_WHO_IS_WHO_DEFAULT_PROTO: http
TZ: UTC
_APP_NAME: myapp
_BUILD_ID: 12345
_DEPLOYMENT_ID: dev--foo.d53
_DEPLOY_ENV: dev
_OTEL_COLLECTOR_URL: tcp://localhost:4317
_POD_ACCOUNT: 12345
_POD_ID: a6127c9c-2be8-4078-8c00-132d29fbecfc
_POD_REGION: us-west-1
_POD_SHORTNAME: us-west-1-dev-default
_TEAM_OWNER: eng-infra
_TRACING_ENABLED: false
force_restart: 2024-01-02T19:00:59Z
GITHUB_PRIVATE_KEY: -----BEGIN RSA PRIVATE KEY-----
fofofofofofofofofofofofofofoofofofofofofofofofoffof
barbabaabababababababababababababababababaababababa
batbababtbabttbtbabtbtabtbtbtbtbtbabtbtbbtbtbtbttbt
-----END RSA PRIVATE KEY-----
这是 Golang 中的单个字符串,以“分隔” ",所以请注意,它不是按
key: value
对排序的。我需要按主键对其进行排序,完成此操作的最佳方法是什么?
我尝试过以下方法:
// sortLines sorts the lines in a blob of text.
func sortLines(blob string) string {
var sorted sort.StringSlice
sorted = strings.Split(blob, "\n")
sorted.Sort()
return strings.Join(sorted, "\n")
}
请注意,由于
GITHUB_PRIVATE_KEY:
包含多行,因此尝试按行排序将不起作用。
嗯,由于未修剪的空格,当前代码无法正常工作 - 它们会影响排序键
您不想在对其他密钥进行排序之前修剪 RSA 密钥吗?如果您怀疑 RSA 密钥始终添加到输入字符串的末尾
希望这会有所帮助:
func SortLines(blob string) string {
gpkSignature := "GITHUB_PRIVATE_KEY:" // github RSA key
gpkIndex := strings.Index(blob, gpkSignature)
return sortLines(blob[:gpkIndex], blob[gpkIndex:])
}
func sortLines(blob, gpk string) string {
var sorted sort.StringSlice
sorted = strings.Split(blob, "\n")
sorted = append(sorted, gpk)
for i := range sorted {
sorted[i] = strings.TrimSpace(sorted[i])
}
sorted.Sort()
return strings.Join(sorted, "\n")
}