【发布时间】:2016-02-10 07:42:42
【问题描述】:
我正在使用具有 JSON api 的 golang 开发 Web 应用程序后端,它位于 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 配置的 location 块中添加了“proxy_buffering off”,它纠正了这个问题。
我的问题:与允许 nginx 处理缓冲并在 Go 中禁用它相比,我是否错过了此设置的任何内容?如果是,我将如何禁用 go server 中的分块?
在我看来,nginx 应该处理分块/压缩/等,而 golang 不应该,但这可能是一个幼稚的假设。任何建议将不胜感激。谢谢!
【问题讨论】:
-
你为什么在这里使用 nginx?
-
对此我没有真正好的答案。这是我进入项目时的设置。我认为最终它的目的是实现负载平衡并拥有多个上游服务器。
-
哦,nginx也处理生产环境中的ssl终止。
-
在 go 中禁用分块编码会很不方便。你要么需要弄清楚为什么你的 nginx 会截断响应(可能是创建临时文件的权限问题),要么像你一样关闭
proxy_buffering。让 Go 进行编码并没有错。 -
谢谢,这解决了我的疑惑。如果您想留下它作为答案,我会接受。