Golang JSON Encoder and nginx proxy buffering

I am working on a backend for a web application in golang that has a JSON api, it is behind nginx 1.8.0.

Nginx Config:

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;
  }
}

I handle routes like:

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

The my checkAuth tool looks like this:

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)
    }
  }
}

And finally, the JSON endpoint, which looks like this:

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)
}

At some point, while working on this, I started getting an error about an incomplete encoded encoding. I am not 100% sure what I changed when I started getting this error. Studying this problem, I found that apparently the go server is processing the response of the response, then nginx will also try to deal with this, causing problems. I added "proxy_buffering off" to the nginx configuration location block and fixed this problem.

: - , nginx Go? , chunking go?

, nginx chunking/compressing/etc golang , , . . !

+3

Source: https://habr.com/ru/post/1615072/


All Articles