golang-如何将数据从默认端口路由到另一个[4000]端口[关闭]

currently my go server is running on port 4000. to access web application i need to type somedomainname:4000 in browser.

I would like to only type somedomainname and it should make the connection to web server on port 4000.

There are several solutions for this:

  1. Have your Go server listen directly on port 80. However, be careful with how you implement this. Do not have your service run as root, but use Linux capabilities instead (thanks to @JimB who reminded me of this in comments). You can use setcap to grant a process the capability to bind to a privileged port:

    > setcap 'cap_net_bind_service=+ep' /path/to/your/application
    
  2. Use an HTTP reverse proxy like Nginx to forward all HTTP requests from port 80 to your Go application. Here's an example configuration file for Nginx:

    upstream yourgoapplication {
      server localhost:4000;
    }
    
    server {
      listen 80;
    
      server_name somedomainname;
    
      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    
        proxy_pass http://yourgoapplication;
      }
    }
    

    When you do this, you can configure to Go application to listen on 127.0.0.1:4000 instead of 0.0.0.0:4000 to make your application accessible only by port 80.

  3. If and when you are deploying your application in a Docker container, you can simply map the container port 4000 to the host port 80. See the manual for more information.