Open rew1nter opened 2 years ago
You can implement this function very simply:
// main.go
package main
import (
"example-project/subdomain"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
serverA := gin.Default()
serverA.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "A")
})
serverB := gin.Default()
serverB.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "B")
})
serverDefault := gin.Default()
serverDefault.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Default")
})
_ = http.ListenAndServe(":8081",
subdomain.NewSubdomainHandler().
On("a.example.com", serverA).
On("b.example.com", serverB).
Default(serverDefault),
)
}
// subdomain/subdomain.go
package subdomain
import (
"net/http"
)
type subdomainHandler struct {
handlers map[string]http.Handler
}
func NewSubdomainHandler() *subdomainHandler {
return &subdomainHandler{handlers: make(map[string]http.Handler, 32)}
}
func (s *subdomainHandler) On(domain string, handler http.Handler) *subdomainHandler {
s.handlers[domain] = handler
return s
}
func (s *subdomainHandler) Default(handler http.Handler) *subdomainHandler {
return s.On("", handler)
}
func (s *subdomainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h, ok := s.handlers[r.Host]; ok {
h.ServeHTTP(w, r)
return
}
if h, ok := s.handlers[""]; ok {
h.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
}
Now, run your program and test it with curl 👇🏻
$ curl -x http://localhost:8081 http://a.example.com
A
$ curl -x http://localhost:8081 http://b.example.com
B
$ curl -x http://localhost:8081 http://c.example.com
Default
Is this how its supposed to be done?