How to run multiple websites at single Go app?

I want to create a system where I can run multiple domains at single Go app. But, the app should show me a different content based on the requesting domain.

Suppose, the app runs on localhost:9090 and all the domains will be pointed to this using nginx reverse proxy. But, I should see totally different content based on incoming website request.

I thought of one way but is looking for another way which might be better.
1 - Save the content & data in DB based on domain
2 - Read the incoming URL and fetch data based on that & show that.

Is it a good model? Please provide your valuable suggestions.

Thanks in advance.



If the sites are static content I suggest looking at Caddy

If you want to dynamically serve content then using the stdlib http listener and router (or one of the 3rd party libraries) should do the trick. Look at Writing Web Applications from the Go blog or LearnServerProgramming from the Go wiki.



If you are looking in a single application, mux, a popular request handling library, can be done this way -

r := mux.NewRouter()
// Only matches if domain is "".
// Matches a dynamic subdomain.

if you need to test this on localhost, you can edit /etc/hosts to add more sub/domain names to verify


Thanks for your replies. I totally fell in love with this forum.

@pieterlouw - I really appreciate you for providing the links but I have already read those and created the website core logic. I was just using different ports to run multiple websites but was avoiding that model as either I had to create a separate executable file for each domain or had to use multiple goroutine in same file.

@sairam - Thanks for the info sairam. I did checked that code earlier too but it will be a part of the concept I am making.

I think in my case a http middleware would be the solution.

How about this logic:
1 - I create a middleware which checks the domain using mux (as @sairam suggested) and search it in DB.
2 - Then, shows the content by setting up the cookies.

I will test it out and let you guys know how it went.

all you need is a reverse proxy. a very simple and functional example:
package main

import (

func main() {
	http.Handle("/a", httputil.NewSingleHostReverseProxy(&url.URL{
		Scheme: "http",
		Host:   "",
	http.Handle("/b", httputil.NewSingleHostReverseProxy(&url.URL{
		Scheme: "http",
		Host:   "",
	http.ListenAndServe(":8080", nil)

also you can use net/http or gorilla/mux` for more complex handlers.

1 Like

Actually, it would be a domain not a URL path that I want to use.

Like: --> localhost:9090 --> localhost:9090

I am using nginx reverse proxy pointing to localhost:9090 now.

you can also use domains.

1 Like

You can also just have the handler inspect r.Header().Get("Host").

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.