Search code examples
httpnginxgoproxyreverse-proxy

Go web server with nginx server in web application


Sorry, I cannot find this answer from Google search and nobody seems to explain clearly the difference between pure Go webserver and nginx reverse proxy. Everybody seems to use nginx in front for web applications.

My question is, while Go has all http serving functions, what is the benefit of using nginx over pure Go web servers?

And in most cases, we set up the Go webserver for all routes here and have the nginx configurations in front.

Something like:

limit_req_zone $binary_remote_addr zone=limit:10m rate=2r/s;

server {
    listen 80;

    log_format lf '[$time_local] $remote_addr ;

    access_log /var/log/nginx/access.log lf;
    error_log /var/log/nginx/error.log;

    set_real_ip_from 0.0.0.0/0;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
    server_name 1.2.3.4 mywebsite.com;
}

When we have this Go:

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Are the traffic to nginx and Go web server different? If not, why do we have two layers of web server?

Please help me understand this.

Thanks,


Solution

  • There's nothing stopping you from serving requests from Go directly.

    On the other hand, there are some features that nginx provides out-of-the box that may be useful, for example:

    • handle many virtual servers (e.g. have go respond on app.example.com and a different app on www.example.com)

    • http basic auth in some paths, say www.example.com/secure

    • access logs

    • etc

    All of this can be done in go but would require programming, while in nginx it's just a matter of editing a .conf file and reloading the configuration. Nginx doesn't even need a restart for this changes to take place.

    (From a "process" point of view, nginx could be managed by an ops employee, with root permissions, running in a well known port, while developers deploy their apps on higher ones.)