✏️ 防止 \r 换行文本过长刷屏

This commit is contained in:
Yiwen-Chan 2021-04-20 16:16:08 +08:00
parent 5d5c13a7e6
commit 26c7719f12

View File

@ -202,7 +202,7 @@ func runCode(code string, runType [2]string) (string, error) {
} }
// 发送请求 // 发送请求
client := &http.Client{ client := &http.Client{
Timeout: time.Duration(6 * time.Second), Timeout: time.Duration(15 * time.Second),
} }
request, _ := http.NewRequest("POST", api, strings.NewReader(val.Encode())) request, _ := http.NewRequest("POST", api, strings.NewReader(val.Encode()))
request.Header = header request.Header = header
@ -221,36 +221,38 @@ func runCode(code string, runType [2]string) (string, error) {
// 结果处理 // 结果处理
content := gjson.ParseBytes(res) content := gjson.ParseBytes(res)
if e := content.Get("errors").Str; e != "\n\n" { if e := content.Get("errors").Str; e != "\n\n" {
return "", fmt.Errorf(e) return "", fmt.Errorf(cutTooLong(clearNewLineSuffix(e)))
} }
output := content.Get("output").Str output := content.Get("output").Str
for strings.HasSuffix(output, "\n") {
output = output[:len(output)-1] return cutTooLong(clearNewLineSuffix(output)), nil
} }
temp := []rune(output)
isCut := false // 清除末尾多余的换行符
if strings.Count(output, "\n") > 30 { func clearNewLineSuffix(text string) string {
count := 0 for strings.HasSuffix(text, "\n") {
for i, r := range temp { text = text[:len(text)-1]
if r == 10 { }
count++ return text
fmt.Println(i) }
}
if count > 30 { // 截断过程文本
temp = temp[:i] func cutTooLong(text string) string {
break temp := []rune(text)
} count := 0
} for i := range temp {
isCut = true switch {
} case temp[i] == 13 && i < len(temp)-1 && temp[i+1] == 10:
if len(temp) > 1000 { // 匹配 \r\n 跳过,等 \n 自己加
// 超长截断 case temp[i] == 10:
temp = temp[:1000] count++
isCut = true case temp[i] == 13:
} count++
if isCut { }
output = string(temp) if count > 30 || i > 1000 {
output += "\n............\n............" temp = append(temp[:i-1], []rune("\n............\n............")...)
} break
return output, nil }
}
return string(temp)
} }