Solon v3.0.1

问题:怎样让 mvc 接口内容支持 gzip 输出?

</> markdown

原理是,定制个渲染器替代默认的。以常见的 http-json 接口为例。以下仅供参考:

@Component
public class GzipFilter implements Filter {

    @Init
    public void init() {
        //注册一个定制的渲染器
        Solon.app().render("@json-gzip", (data, ctx) -> {
            //借用 json 渲染器(可隔离具体的 json 框架),生成 json
            String json = Solon.app().renderOfJson().renderAndReturn(data, ctx);
            
            if(json == null) {
                //这里要不要处理,视业务而定
                return;
            }
            
            //可以用 json 的长度做条件是否用 gzip?
            if(json.length() > 1024) {
                //输出压缩流
                GZIPOutputStream gzip = ctx.outputStreamAsGzip();
                gzip.write(json.getBytes());
                gzip.finish(); //不要 close
            } else {
                //不压缩
                ctx.output(json);
            }
        });
    }

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        //指定当前渲染用 @json-gzip
        ctx.attrSet("@render", "@json-gzip");
        
        chain.doFilter(ctx);
    }
}