在 Web 服务器前使用 Nginx 对 Go 有什么好处?

我正在编写一些返回 JSON 数据的 Web 服务,它们有很多用户。

与仅仅使用 http 服务器相比,在服务器前使用 Nginx 的好处是什么?

40124 次浏览

The standard http server of Go is fine. If your application mostly/only are "dynamic" requests/responses, then it's really the best way.

You could use nginx to serve static assets, but most likely the standard Go one is fine for that, too. If you need higher performance you should just use a CDN or cache as much as you can with Varnish (for example).

If you need to serve different applications off the same IP address, nginx is a fine choice for a proxy to distribute requests between the different applications; though I'd more often get Varnish or HAProxy out of the toolbox for that sort of thing.

It depends.

Out of the box, putting nginx in front as a reverse proxy is going to give you:

  • Access logs
  • Error logs
  • Easy SSL termination
  • SPDY support
  • gzip support
  • Easy ways to set HTTP headers for certain routes in a couple of lines
  • Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)

The Go HTTP server is very good, but you will need to reinvent the wheel to do some of these things (which is fine: it's not meant to be everything to everyone).

I've always found it easier to put nginx in front—which is what it is good at—and let it do the "web server" stuff. My Go application does the application stuff, and only the bare minimum of headers/etc. that it needs to. Don't look at putting nginx in front as a "bad" thing.

The Gorilla web toolkit gives you:

  • Advanced routing (domain/subdomain restriction, regex path matching).
  • gzip support (via middleware handlers.)
  • Logging middleware handler that outputs in Apache Common Log Format.
  • Secure encrypted cookies.
  • Sessions.
  • schema package converts form values to a struct.

This fills much gap between Go's net/http and HTTP servers like NGINX.

Personally, I'd avoid installing and configuring another HTTP server on top of net/http if I know I can plug in a CDN instead.

I think net/http has the most powerful HTTP server in any standard library.

From https://blog.gopheracademy.com/caddy-a-look-inside/ it looks like Go can handle gzip, errors, static files, routing and http headers using Middleware. The line below, from the blog, show how you would handle such a request.

logHandler(gzipHandler(fileServer))

They handle error logging in a really interesting way. As long as your middleware returns an error code (int), the error-handling middleware automatically handles it. They've even gone as far as configuring the whole site in Go like Nginx would. "The nginx.conf file for all the Gopher Academy websites was over 115 lines long. The equivalent Caddyfile is only 50 lines."