gin icon indicating copy to clipboard operation
gin copied to clipboard

How to use multiple domains?

Open taobil opened this issue 7 years ago • 4 comments

How to use multiple domains with one port ?

taobil avatar Oct 15 '18 01:10 taobil

Such as : type AdminController struct // portal.domain.com

type BlogController struct // blog.domain.com

ghost avatar Oct 15 '18 01:10 ghost

@getkokomi please check #347

thinkerou avatar Oct 15 '18 23:10 thinkerou

Maybe, the question meaning is: How to use dynamic/wildcard subdomains?

wahello avatar Sep 15 '19 07:09 wahello

Use HostSwitch to host multiple domains.

import (
    "fmt"
    "log"
    "net/http"
)

type HostSwitch map[string]http.Handler

// Implement the ServerHTTP method
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if handler, ok := hs[r.Host]; ok && handler != nil {
        handler.ServeHTTP(w, r)
    } else {
        http.Error(w, "Forbidden", http.StatusForbidden)
    }
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the first home page!")
	})

	muxTwo := http.NewServeMux()
	muxTwo.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the second home page!")
	})

    hs := make(HostSwitch)
    hs["example-one.local:8080"] = mux
    hs["example-two.local:8080"] = muxTwo

    log.Fatal(http.ListenAndServe(":8080", hs))
}

More info here

zelenko avatar Aug 09 '24 22:08 zelenko