Go supports built-in server. But there is a limitation that you can host only one site at once with one port.
Though you can host multiple sites with the domain name using gorilla mux then all site will come with one app that will be very hard to maintain and update.
Another option is you can host your site with different ports and then use the reverse proxy to map to map the domain name to the port
ScenarioI have two sites running on my vultr vps. All of them are website that means request will be come in with domain name and going to be arrived on the port 80. If I assing one program [ site ] to listen to the port 80 others will not be able to listen on port 80.
Requirement is that requests should be listend on port 80 and handled by the app to which it relates.
After struggling for 3 days i got this 😂 silly solution.
Source Code ( solution I got )
Compiled binary of this code is proxy server for us
Explanation Of CodeWe are using http package and httputil package to make this done.
I assign my every sites port in serise of 80xx
- gospot.mchampaneri.in is listening on 8085
- temp.mchampaneri.in is listening on 8081
Now Created another golang app which works as http mux .
[ Which's Source Code I am Showing. Ya It Just 17+ 😁(imports + package main) lines for me]
Explanation of the core code
u1, _ := url.Parse("http://localhost:8085/")In this line we are parsing the url of our end point
[my app of gospot.mchampaneri.in is running on local 8085 port]
http.Handle("gospot.mchampaneri.in/", httputil.NewSingleHostReverseProxy(u1))It matches the request with the .Handle( input-url ) and if matches it forwards the request to the url which we parsed before.
Explaination of WorkAfter seeing code if still you are confused how it works, let me explaing the flow.
- You search for gospot.mchampaner.in in you browser
- DNS server will forward request to my vultu vps on port 80
- Our Proxy is running on port 80 it will receive request
- Proxy will match the request with the http.Handle("gospot.mchampaneri.in/") and so request will be handled by httputil.NewSignelHostReverseProxy(u1) [ which is actully the reverse proxy]
So inshort this proxy will map incomming request domain to the port on your vps which is inteded to handle it.
Hope you will find it usefull and easy to understand.
For this post your comments are welcomed so i can make it better.