猿问

多余的回应。写头呼叫状态OK

在我的代码中,我有一个循环来处理文件集(基于预先指定的文件夹中可用的文件),并根据每个处理文件的输出,将一些信息发送到客户端,所以我写了以下内容:


    for i, file := range files {

        uniqueSlice := unique(matches)

        output = Output{MSG: "ok", File: file, Skills: uniqueSlice}

        data, err := json.Marshal(output)

        if err != nil {

            panic(err)

        }

        w.Header().Set("Content-Type", "application/json")

        w.WriteHeader(http.StatusOK) // -< Error from here

        w.Write(data)

    }

如果文件夹有一个文件,上面工作正常,但如果有多个文件,我得到了错误:我明白错误是由于使用其中不能多次使用来设置,但我需要设置它,以便客户端处理返回的数据。http: superfluous response.WriteHeader callw.WriteHeader(http.StatusOK)


如何修复此代码,以便在处理每个文件时可以直接向客户端返回数据。


更新如果我按照下面评论中的建议删除,那么我会得到返回的纯文本而不是JSON!http.StatusOK


繁星淼淼
浏览 144回答 1
1回答

慕丝7291255

您不能只是将 JSON 文档连接在一起,并期望结果是有效的 json 编码。您必须将对象放在数组中,然后在最后输出该数组一次,否则响应将不是有效的 json。output如果像代码一样单独输出对象,则最终数据将如下所示{"MSG": "ok", "File": "...", "Skills": [...]}{"MSG": "ok", "File": "...", "Skills": [...]}{"MSG": "ok", "File": "...", "Skills": [...]}这些输出中的每一个本身都是有效的,但整个输出(对象只是连接在一起)却不是。理想情况下,在将 json 输出到像 HTTP 响应这样的流时,不要将其存储在中间缓冲区 () 中,而是使用 http 响应编写器。流式处理几乎总是比渲染到变量更好。datajson.NewEncoder(w)w&nbsp; &nbsp; var outputs = make([]Output,0,len(files)&nbsp; &nbsp; for i, file := range files {&nbsp; &nbsp; &nbsp; &nbsp; uniqueSlice := unique(matches)&nbsp; &nbsp; &nbsp; &nbsp; outputs = append(outputs, Output{MSG: "ok", File: file, Skills: uniqueSlice})&nbsp; &nbsp; }&nbsp; &nbsp; w.Header().Set("Content-Type", "application/json")&nbsp; &nbsp; w.WriteHeader(http.StatusOK)&nbsp; &nbsp; if err := json.NewEncoder(w).Encode(outputs); err != nil {&nbsp; &nbsp; &nbsp; &nbsp;panic(err)&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Go
我要回答