Skip to content

Commit df06d82

Browse files
committed
feat: 接口统一返回格式添加 path 信息
1 parent 41c0301 commit df06d82

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

src/main/java/info/cadecode/simple/common/response/SimpleResAdvice.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import org.springframework.web.bind.annotation.ControllerAdvice;
99
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
1010

11+
import java.net.URI;
12+
1113
/**
1214
* @author Cade Li
1315
* @date 2021/7/16
@@ -27,13 +29,18 @@ public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType
2729
// 设置统一的 Content-Type
2830
HttpHeaders headers = response.getHeaders();
2931
headers.setContentType(MediaType.APPLICATION_JSON);
30-
32+
// 获取请求路径
33+
String path = request.getURI().getPath();
34+
// 判断 body 类型分别处理
3135
if (body instanceof SimpleRes) {
32-
return body;
36+
return ((SimpleRes) body).path(path);
3337
}
38+
// String 类型的 Body 需要返回 String 类型,否则报转换错误
3439
if (body instanceof String) {
35-
return SimpleRes.ok(body).json();
40+
return SimpleRes.ok(body)
41+
.path(path)
42+
.json();
3643
}
37-
return SimpleRes.ok(body);
44+
return SimpleRes.ok(body).path(path);
3845
}
3946
}

0 commit comments

Comments
 (0)