Host Multiple Golang Sites on One IP and Serve Depending on Domain Request?
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)
}
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