All Downloads are FREE. Search and download functionalities are using the official Maven repository.

club.zhcs.hanlder.GlobalResponseHandler Maven / Gradle / Ivy

package club.zhcs.hanlder;

import java.util.List;
import java.util.regex.Pattern;

import org.nutz.lang.Lang;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import club.zhcs.Result;

/**
 * @author 王贵源([email protected])
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice {

    List ignorePaths;

    static final List DEFAULT_IGNORED_PATH = Lang.list("/swagger-resources.*",
                                                               "/swagger-customer.*",
                                                               "/v2/api-docs",
                                                               "/actuator.*");

    /**
     * @param ignorePaths
     *            忽略的路径
     */
    public GlobalResponseHandler(List ignorePaths) {
        if (ignorePaths == null || ignorePaths.isEmpty()) {
            ignorePaths = DEFAULT_IGNORED_PATH;
        }
        ignorePaths.addAll(DEFAULT_IGNORED_PATH);
        this.ignorePaths = ignorePaths;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body instanceof Result || ignored(request.getURI().getRawPath())) {
            return body;
        }
        return Result.success(body);

    }

    /**
     * @param rawPath
     * @return
     */
    private boolean ignored(String path) {
        return ignorePaths.stream().anyMatch(item -> Pattern.matches(item, path));
    }

}