如何在 kottpd 中正确定义 REST 资源
How to properly define REST resources in kottpd
我正在使用 kottpd
在 Kotlin 中开发 REST 服务器
这是我定义的资源/URI 的摘录:
get("/patients") {req, res -> PatientHandler.doGetAll(req, res)}
post("/patients") {req, res -> PatientHandler.doPost(req, res)}
get("/patients/.*") {req, res -> PatientHandler.doGetOne(req, res)}
post("/patients/.*") {req, res -> PatientHandler.doPatch(req, res)}
get("/patients/.*/cases") {req, res -> CaseHandler.doGetAll(req, res)}
post("/patients/.*/cases") {req, res -> CaseHandler.doPost(req, res)}
/patients
和 /patients/.*
到目前为止工作正常:例如
POST: /patients
将患者添加到列表并 GET: /patients/1
检索 ID 为 1 的患者。
然而,当调用 POST: /patients/1/cases
为患者 1 添加病例时,执行附加到 POST: /patients/.*
的函数。
我假设(!).*
是一个通配符,因此在 ID、更多路径或其他任何东西之间没有区别。
如何定义我的资源/URI 以区分这些情况?
或者,如果我的假设不正确:我做错了什么?
解决方案是将 .*
替换为 \d+
,
例如。 GET: /patients/\d+/cases
或 get("/patients/\d+/cases")
正如 u/8bitlives 在 reddit 上指出的那样:
Seems like the paths are used as pure regex patterns. So .* is "anything 0 or more times". Replacing the wildcard with a more precise \d+ meaning "one or more numbers". I'd suggest writing the paths avoidin the wildcard altogether. And using a service like regex101.com to validate the patterns.
我正在使用 kottpd
在 Kotlin 中开发 REST 服务器这是我定义的资源/URI 的摘录:
get("/patients") {req, res -> PatientHandler.doGetAll(req, res)}
post("/patients") {req, res -> PatientHandler.doPost(req, res)}
get("/patients/.*") {req, res -> PatientHandler.doGetOne(req, res)}
post("/patients/.*") {req, res -> PatientHandler.doPatch(req, res)}
get("/patients/.*/cases") {req, res -> CaseHandler.doGetAll(req, res)}
post("/patients/.*/cases") {req, res -> CaseHandler.doPost(req, res)}
/patients
和 /patients/.*
到目前为止工作正常:例如
POST: /patients
将患者添加到列表并 GET: /patients/1
检索 ID 为 1 的患者。
然而,当调用 POST: /patients/1/cases
为患者 1 添加病例时,执行附加到 POST: /patients/.*
的函数。
我假设(!).*
是一个通配符,因此在 ID、更多路径或其他任何东西之间没有区别。
如何定义我的资源/URI 以区分这些情况? 或者,如果我的假设不正确:我做错了什么?
解决方案是将 .*
替换为 \d+
,
例如。 GET: /patients/\d+/cases
或 get("/patients/\d+/cases")
正如 u/8bitlives 在 reddit 上指出的那样:
Seems like the paths are used as pure regex patterns. So .* is "anything 0 or more times". Replacing the wildcard with a more precise \d+ meaning "one or more numbers". I'd suggest writing the paths avoidin the wildcard altogether. And using a service like regex101.com to validate the patterns.