Handle sub domains in go.

1,502 views
Skip to first unread message

Swati Sharma

unread,
Oct 27, 2017, 8:16:18 AM10/27/17
to golang-nuts

Hello
I am working on a project where I need to setup the multiple sub-domains with the routes. For routing I am using gin package.  I tried code with two sub-domains, but in my case it would be 100 sub-domains. I tried the following code for this:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "strings"
)

type Subdomains map[string]http.Handler

func (subdomains Subdomains) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    domainParts := strings.Split(r.Host, ".")

    if mux := subdomains[domainParts[0]]; mux != nil {
        mux.ServeHTTP(w, r)
    } else {
        http.Error(w, "Not found", 404)
    }
}

func main() {
    r := gin.Default()
    r2 := gin.Default()
    hs := make(Subdomains)
    hs["admin"] = r
    hs["analytics"] = r2
    r.GET("/ping", adminHandlerOne)
    r2.GET("/ping", adminHandlerOne)
    http.ListenAndServe(":9090", hs)
}
func adminHandlerOne(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "pong",
    })
}

But I think that this is not good. Is anybody know the proper way to do this?
I tried to do this with loop also, but it did't work for me.

Jonathan Yu

unread,
Oct 27, 2017, 11:03:09 AM10/27/17
to Swati Sharma, golang-nuts
I don't use gin (I use chi) but from the docs it seems gin is based on httprouter, and thus maybe this pattern/example is useful? https://github.com/julienschmidt/httprouter#multi-domain--sub-domains (looks very similar to yours, though - only difference is that this example uses the fully-qualified hostname instead of just the first part)

Chi provides a middleware for doing this: https://github.com/go-chi/hostrouter - the source code might help you with what you're doing? https://github.com/go-chi/hostrouter/blob/master/hostrouter.go

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Jonathan Yu @jawnsy on LinkedInTwitterGitHubFacebook
“Ever tried. Ever failed. No matter. Try again. Fail again. Fail better.” — Samuel Beckett, Worstward Ho (1983) 

“In an adaptive environment, winning comes from adapting to change by continuously experimenting and identifying new options more quickly and economically than others. The classical strategist's mantra of sustainable competitive advantage becomes one of serial temporary advantage.” — Navigating the Dozens of Different Strategy Options (HBR)
Reply all
Reply to author
Forward
0 new messages