0

I wish to be able to do the following:

mydomain.com/this/that

Should redirect differently to:

a.sub.domain.mydomain.com/this/that

I see Express has the following:

github.com/bmullan91/express-subdomain

Koa does have one:

github.com/demohi/koa-subdomain

As you can see it's pretty dead. Anyway to achieve this while using Koa?

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • Your question is not clear, routing is not related to domains in any way, post your code please... – Willem D'Haeseleer Apr 23 '15 at 21:52
  • 1
    @ Karl Morrison: Did you notice there is a new koa-sub-domain plugin @Danny made? The last answer contains your perfect solution. I used it - and it is great work ! –  Jun 29 '15 at 09:49

2 Answers2

5

you can write a subdomain-middleware to achieve this.

var koa = require('koa');
var app = koa();


routeMain = function *(next) {
    this.body = 'mydomain.com';
};


routeSub = function *(next) {
    this.body = 'sub.mydomain.com';
};


// subdomain middleware
subdomain = function (domain,route){
    return function *(next){
        var s=this.subdomains[0] || '';
        if (s === domain) {
            yield route.call(this,next);
        }
        else{
            yield next;
        }
    };
};


app.use(subdomain('sub', routeSub));
app.use(subdomain('', routeMain));

app.use(function *(next){
    console.log("done");
});


app.listen(3000);
Larvata
  • 169
  • 4
  • 2
    @Larvata: I am confused about the line `var s=this.subdomains[0] || '';` how does this work ? Is Koa doing this by collecting all app.use(subdomain and stacking this into the this.subdomains array ? – Danny Jun 20 '15 at 14:55
  • 3
    @Danny: because Koa is creating a `this-context` for each request, there is at least one entry in the `this.subdomains[]` array. The `this.subdomains` is not created from the `app.use` - it is an array because it contains also the sub sub sub domains ... e.g. `this.subdomains['bar','foo']` for `foo.bar.example.com` –  Jun 20 '15 at 20:18
1

I am very proud to present my first middleware for koa

Koa-Sub-Domain

inspired by express-subdomain but with some more flexibility about wildcards and using generator function instead of routers. It is developed to work well with Koa-router!

Danny
  • 1,078
  • 7
  • 22
  • 1
    I will def check this out! – basickarl Jun 30 '15 at 15:11
  • 1
    @KarlMorrison: cool - let me know whether this answers your question. Also feel free to add wishes as issues - I organize further development with integrated project management. Your feedback is very welcome ! – Danny Jun 30 '15 at 15:19