dreamhead / moco

Easy Setup Stub Server
MIT License
4.36k stars 1.08k forks source link

如何加入自己实现的ResponseHandler?我想要对返回进行签名。 #274

Closed waitshang closed 4 years ago

waitshang commented 4 years ago

如何加入自己实现的ResponseHandler?我想要对返回进行签名。

dreamhead commented 4 years ago

ResponseHandler is an interface which provides you request and response. You can simply write your own class to implement this interface. The basic idea is to write anything to response.

If your request is an HTTP request, you can write a class to extend AbstractHttpResponseHandler and override doWriteToResponse method.

if you just want to write content, you can write a class to extend AbstractContentResponseHandler and override responseContent and getContentType.

waitshang commented 4 years ago

ResponseHandler is an interface which provides you request and response. You can simply write your own class to implement this interface. The basic idea is to write anything to response.

If your request is an HTTP request, you can write a class to extend AbstractHttpResponseHandler and override doWriteToResponse method.

if you just want to write content, you can write a class to extend AbstractContentResponseHandler and override responseContent and getContentType.

Where and how to invoke the implemented ResponseHandler class?

dreamhead commented 4 years ago

@waitshang You can attach your response handler to response setting.

server.response(new YourCustomResponseHandler());
waitshang commented 4 years ago

@waitshang You can attach your response handler to response setting.

server.response(new YourCustomResponseHandler());

Thank you very much.

waitshang commented 4 years ago

@waitshang You can attach your response handler to response setting.

server.response(new YourCustomResponseHandler());

@dreamhead Could I config response like this:

server.request(by(uri("/hello"))).response(template("${req.method}")).response(new MyResponseHandler());

Where MyResponseHandler modify my template at last.

dreamhead commented 4 years ago

Moco provides functional style API which you can composite your API.

server.request(by(uri("/hello"))).response(and(with(template("${req.method}")), new MyResponseHandler()));
waitshang commented 4 years ago

Moco provides functional style API which you can composite your API.

server.request(by(uri("/hello"))).response(and(with(template("${req.method}")), new MyResponseHandler()));

There is a method in DefaultMutableHttpResponse which avoid me to mutate the response's MessageContent.

    @Override
    public void setContent(final MessageContent content) {
        if (this.content != null) {
            throw new IllegalArgumentException("Content has been set");
        }

        this.content = content;
    }