使用枚举限制允许的 httpMethods
Restrict allowed httpMethods using enum
我正在为 REST API 方法创建连接器。有些方法具有相同的方法名称但执行不同的 HTTP 方法。
例如,createEntity( HttpMethod httpMethod, CreateEntity model )
只能执行POST和GET。我想要的是在 httpMethod
与 PUT 或 DELETE 一起提供时出现错误。允许的 httpMethod
将取决于每种方法。我如何在 CreateEntity.groovy
?
中进行验证
这里是HttpMethod.groovy
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
CreateEntity.groovy
private String field1;
private String field2;
//write here that only POST and GET are allowed
Connector.groovy
def createEntityQuery ( HttpMethod httpMethod, CreateEntityQuery model ) {
//perform operations
}
这必须有效:
createEntity( HttpMethod.POST, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.GET, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
这应该会引发错误:
createEntity( HttpMethod.PUT, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.DELETE, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
是您要找的吗:
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
class EntityQuery {
String field1
String field2
}
def createEntity(HttpMethod h, EntityQuery q) {
if(!(h in [HttpMethod.POST, HttpMethod.GET])) {
throw new Exception('Only POST and GET methods allowed')
}
}
createEntity(HttpMethod.PUT, new EntityQuery())
?
然而,最好公开 public 方法,例如 createPostEntity
或 createGetEntity
,它们将只接受 EntityQuery
作为参数,而 HttpMethod
将在内部处理。
我正在为 REST API 方法创建连接器。有些方法具有相同的方法名称但执行不同的 HTTP 方法。
例如,createEntity( HttpMethod httpMethod, CreateEntity model )
只能执行POST和GET。我想要的是在 httpMethod
与 PUT 或 DELETE 一起提供时出现错误。允许的 httpMethod
将取决于每种方法。我如何在 CreateEntity.groovy
?
这里是HttpMethod.groovy
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
CreateEntity.groovy
private String field1;
private String field2;
//write here that only POST and GET are allowed
Connector.groovy
def createEntityQuery ( HttpMethod httpMethod, CreateEntityQuery model ) {
//perform operations
}
这必须有效:
createEntity( HttpMethod.POST, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.GET, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
这应该会引发错误:
createEntity( HttpMethod.PUT, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.DELETE, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
是您要找的吗:
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
class EntityQuery {
String field1
String field2
}
def createEntity(HttpMethod h, EntityQuery q) {
if(!(h in [HttpMethod.POST, HttpMethod.GET])) {
throw new Exception('Only POST and GET methods allowed')
}
}
createEntity(HttpMethod.PUT, new EntityQuery())
?
然而,最好公开 public 方法,例如 createPostEntity
或 createGetEntity
,它们将只接受 EntityQuery
作为参数,而 HttpMethod
将在内部处理。