gpt4 book ai didi

json - Golang JSON 编码器和 nginx 代理缓冲

转载 作者:IT王子 更新时间:2023-10-29 01:15:30 25 4
gpt4 key购买 nike

我正在 golang 中开发一个具有 JSON api 的网络应用程序后端,它位于 nginx 1.8.0 之后。

Nginx 配置:

server {

listen 80;
server_name someserver.com;

location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8080;

# The go server handles the chunking, so with proxy_buffering on it messes up the response
proxy_buffering off;
}
}

我处理这样的路线:

router.GET("/api/cases", checkAuth(api.GetAllCases))

我的 checkAuth 中间件看起来像:

func checkAuth(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
url := strings.Split(r.URL.String(), "/")
if notAuthenticatedCode {
http.Error(w, "", http.StatusUnauthorized)
} else {
if url[1] == "api" {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
} else {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
h(w, r, ps)
}
}
}

最后,一个 JSON 端点如下所示:

func (api API) GetAllCases(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// It used to write the json in a different manner, I think this
// is where I started receiving the error when I changed to this
json.NewEncoder(w).Encode(Cases)
}

在处理此问题的某个时候,我开始收到有关不完整的分块编码的错误。当我开始收到此错误时,我不是 100% 确定我更改了什么。在调查这个问题时,我发现显然 go 服务器正在处理响应分块,然后 nginx 也会尝试处理它导致问题。我在 nginx 配置的位置 block 中添加了“proxy_buffering off”,它纠正了这个问题。

我的问题:与允许 nginx 处理缓冲并在 Go 中禁用它相比,我是否错过了此设置的任何内容?如果是,我将如何禁用 go 服务器中的分块?

在我看来,nginx 应该处理分块/压缩/等等,而 golang 不应该,但这可能是一个天真的假设。任何建议将不胜感激。谢谢!

最佳答案

如果响应体小于default buffer size (4k) ,尝试设置 proxy_buffer_size 以减小缓冲区大小。

关于json - Golang JSON 编码器和 nginx 代理缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com