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

club.zhcs.lina.web.response.GlobalResponseHandler Maven / Gradle / Ivy

The newest version!
package club.zhcs.lina.web.response;

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.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 
 * @author Kerbores([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(@NonNull MethodParameter returnType, @NonNull Class> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(@Nullable Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class> selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull 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));
    }

}