将静态中间件与Tink Web一起使用

时间:2019-05-22 12:38:28

标签: haxe

我想声明2条路线。第一个"/api"将提供一些REST内容,而另一个"/static"应该提供静态内容。

我试图从快速入门示例开始,但是我不知道该怎么做。

import tink.http.containers.*;
import tink.http.Response;
import tink.web.routing.*;

class Server {
    static function main() {
        var container = new NodeContainer(8080);
        var router = new Router<Root>(new Root());
        container.run(function(req) {
            return router.route(Context.ofRequest(req))
                .recover(OutgoingResponse.reportError);
        });
    }
}

class Root {
    public function new() {}

    @:get('/')
    @:get('/$name')
    public function hello(name = 'World')
        return 'Hello, $name!';
}

2 个答案:

答案 0 :(得分:4)

对于/static,您可以使用tink_http_middleware中的Static
对于/api,您可以使用@:sub路由。

import tink.http.containers.*;
import tink.http.Handler;
import tink.http.Response;
import tink.http.middleware.Static;
import tink.web.routing.*;

class Server {
    static function main() {
        var container = new NodeContainer(8080);
        var router = new Router<Api>(new Api());
        var handler:Handler = req -> router.route(Context.ofRequest(req)).recover(OutgoingResponse.reportError);
        container.run(handler.applyMiddleware(new Static('public_html', '/static')));
    }
}

class Api {
    @:sub public var api:Root = new Root();
}

class Root {
    public function new() {}

    @:get('/')
    @:get('/$name')
    public function hello(name = 'World')
        return 'Hello, $name!';
}

答案 1 :(得分:1)

首先,我必须使用tink_http_middleware和asys的git版本

-lib tink_web
-lib hxnodejs
-lib tink_http_middleware:git:https://github.com/haxetink/tink_http_middleware.git
-lib asys:git:https://github.com/benmerckx/asys.git
-main server.Api
-js www/api/api.js

接下来,@ KevinResoL的回答非常有帮助,我只更改了一件事。 staticMiddleware.apply(处理程序)

package server;

import tink.http.Handler;
import tink.http.middleware.Static;
import tink.http.containers.*;
import tink.http.Response;
import tink.web.routing.*;

class Api {
    public static function main() {

        var container = new NodeContainer(8080);
        var router = new Router<ApiRoute>(new ApiRoute());
        var staticMiddleware = new Static("..","/");
        var handler:Handler = req -> router.route(Context.ofRequest(req)).recover(OutgoingResponse.reportError);
        container.run(staticMiddleware.apply(handler));
    }
}

class ApiRoute {
    public function new() { }

    @:sub public var api:Root = new Root();
}

class Root {

    public function new() { }

    @:get('/')
    @:get('/$name')
    public function serve(name = 'index.html')
        return 'Hello, $name!';
}