donglei2022
2016-10-06 10:57
浏览 82
已采纳

在一个IP上托管多个Golang站点并根据域请求提供服务?

I'm running a VPS with Ubuntu installed. How can I use the same VPS (same IP) to serve multiple Golang websites without specifying the port (xxx.xxx.xxx.xxx:8084) in the url?

For example, Golang app 1 is listening on port 8084 and Golang app 2 is listening on port 8060. I want Golang app 1 to be served when someone requests from domain example1.com and Golang app 2 to be served when someone requests from domain example2.com.

I'm sure you can do this with Nginx but I haven't been able to figure out how.

图片转代码服务由CSDN问答提供 功能建议

我正在安装Ubuntu的情况下运行VPS。

如何在不指定网址的端口(xxx.xxx.xxx.xxx:8084)的情况下使用相同的VPS(相同的IP)来服务多个Golang网站?

例如,< strong> Golang应用程序1正在监听端口8084 ,而 Golang应用程序2正在监听端口8060 。 我希望有人从域 example1.com 请求提供Golang应用程序1,有人从域 example2.com 请求提供Golang应用程序2。

我确定您可以使用Nginx进行此操作,但我无法弄清楚该怎么做。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dounue1965 2016-10-06 11:17
    已采纳

    Please, try out the following code,

    server {
       ...
       server_name www.example1.com example1.com;
       ...
       location / {
          proxy_pass app_ip:8084;
       }
       ...
    }
    
    ...
    
    server {
       ...
       server_name www.example2.com example2.com;
       ...
       location / {
          proxy_pass app_ip:8060;
       }
       ...
    }
    

    app_ip is the ip of the machine wherever same is hosted, if on the same machine, put http://127.0.0.1 or http://localhost

    点赞 评论
  • douhui2307 2016-10-06 21:35

    Nginx free solution.

    First of all you can redirect connections on port 80 as a normal user

    sudo apt-get install iptables-persistent
    sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000
    sudo netfilter-persistent save
    sudo netfilter-persistent reload
    

    Then use gorilla/mux or similar to create a route for every host and even get a "subrouter" from it

    r := mux.NewRouter()
    s := r.Host("www.example.com").Subrouter()
    

    So the complete solution would be

    package main
    
    import (
        "net/http"
        "github.com/gorilla/mux"
        "fmt"
    )
    
    func Example1IndexHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello www.example1.com!") // send data to client side
    }
    
    func Example2IndexHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello www.example2.com!") // send data to client side
    }
    
    func main() {
        r := mux.NewRouter()
        s1 := r.Host("www.example1.com").Subrouter()
        s2 := r.Host("www.example2.com").Subrouter()
    
        s1.HandleFunc("/", Example1IndexHandler)
        s2.HandleFunc("/", Example2IndexHandler)
    
        http.ListenAndServe(":8000", nil)
    }
    
    点赞 评论

相关推荐 更多相似问题