如何将数据从默认端口路由到另一个端口(4000)的Golang代码?

huangapple go评论84阅读模式
英文:

golang - how to route data from default port to another[4000] port

问题

目前我的Go服务器正在4000端口上运行。要访问Web应用程序,我需要在浏览器中输入somedomainname:4000

我希望只需输入somedomainname,它就可以连接到4000端口上的Web服务器。

英文:

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.

答案1

得分: 4

有几种解决方案:

  1. 让你的Go服务器直接监听80端口。但是,在实现时要小心。不要将服务以root身份运行,而是使用Linux capabilities(感谢@JimB在评论中提醒我)。你可以使用setcap命令授予进程绑定特权端口的能力:

    > setcap 'cap_net_bind_service=+ep' /path/to/your/application
    
  2. 使用像Nginx这样的HTTP反向代理,将所有的HTTP请求从80端口转发到你的Go应用程序。这是一个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;
      }
    }
    

    这样做时,你可以配置Go应用程序监听127.0.0.1:4000而不是0.0.0.0:4000,使你的应用程序只能通过80端口访问。

  3. 如果你将应用程序部署在Docker容器中,你可以简单地将容器的4000端口映射到主机的80端口。请参阅手册获取更多信息。

英文:

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.

huangapple
  • 本文由 发表于 2016年1月4日 20:31:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/34591237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定