我创建了一个函数,用于将特定的字符串(从[]字节派生)转换为结构。在程序中,我正在构建加密和解密,并且在这两个通道之间通过JSON传输数据。我提出的功能可以工作,但是在字符串变得很长的时候,处理时间很长。 我想问的是,是否有人知道如何加快此功能或如何更好地处理这种情况。
这是功能
func Datadecrypt(input []byte) Data {
s := string(input)
vals := strings.Replace(s," "," ",-1)
part := strings.Fields(vals)
c := strings.Split(s, "int=")[1]
co := strings.Split(c, ")")[0]
count, err := strconv.Atoi(co)
if err != nil {
log.Fatal(err)
}
var stringa string
for j := 0; j<len(part); j++ {
if strings.ContainsAny(part[j], ":") {
stringa = stringa+" "+part[j]
} else {
stringa = stringa+","+part[j]
}
}
var interpart []map[string]string
var result Data
var i = 0
for {
split := strings.Split(stringa, "[")[2+i]
splitend := strings.Split(split, "]")[0]
control := strings.Replace(splitend," "," ",-1)
mapst := mapstring.StrToMS(control)
interpart = append(interpart, mapst)
i++
if i >= count {
break
}
}
result = Data{Count: count, Results: interpart}
return result
}
这是结构
type Data struct {
Count int `json:"count"`
Results []map[string]string `json:"result"`
}
这是从s派生的字符串:=字符串(输入)
"Count=\"%!s(int=107)\"\nResults=\"[map[MATRICOLA:2 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:7 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:5 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:6 NOMEmy:value COGNOMEmy:value]]\"\n"
我上面写的字符串是使用JSON响应打印的
这是输入字符串NOT JSON
Count="%!s(int=107)"
Results="[map[MATRICOLA:2 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:7 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:5 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:6 NOMEmy:value COGNOMEmy:value]]"
这是我通过函数得到的结果
{107 map[MATRICOLA:2 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:7 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:5 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:6 NOMEmy:value COGNOMEmy:value]]}
预先感谢
答案 0 :(得分:0)
这不是您问题的答案,但可能是您问题的解决方案。如果我完全错了,请发表评论。
输入字符串看起来像是通过fmt.Printf()
生成的
"Count=\"%!s(int=107)\"\nResults=\"[map[MATRICOLA:2 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:7 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:5 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:6 NOMEmy:value COGNOMEmy:value]]\"\n"
https://play.golang.org/p/pRWUtRKikEh
count := 107
results := "[map[MATRICOLA:2 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:7 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:5 NOMEmy:value COGNOMEmy:value] map[MATRICOLA:6 NOMEmy:value COGNOMEmy:value]]"
fmt.Printf("Count=%s\nResults=%s", count, results)
因此,如果您能够将打印语句更改为fmt.Printf("Count=%d\nResults=%s", count, results)
,则输出将正确。
https://play.golang.org/p/g45_TiHMFsG