Host Multiple Golang Sites on One IP and Serve Dep

2019-05-11 03:12发布

问题:

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.

回答1:

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



回答2:

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)
}


标签: http nginx go port