我想使用Ratpack创建一个“模拟”服务器。
首先,我正在从一个文件夹中读取并定义一对配对列表,每一对都有:
我想启动一个定义这些路由和响应的服务器:
// this is already done; returns smth such as:
def getServerRules() {
[ path: "/books", response: [...] ],
[ path: "/books/42", response: [ title: "this is a mock" ] ],
[ path: "/books/42/reviews", response: [ ... ] ],
...
]
def run() {
def rules = getServerRules()
ratpack {
handlers {
get( ??? rule.path ??? ) {
render json( ??? rule.response ??? )
}
}
}
}
我可以迭代那些rules
以便以某种方式为每个项目定义处理程序吗?
答案 0 :(得分:3)
您可以通过迭代定义的服务器规则列表来定义所有处理程序,就像在这个Ratpack Groovy脚本中一样:
@Grapes([
@Grab('io.ratpack:ratpack-groovy:1.5.0'),
@Grab('org.slf4j:slf4j-simple:1.7.25'),
@Grab('org.codehaus.groovy:groovy-all:2.4.12'),
@Grab('com.google.guava:guava:23.0'),
])
import static ratpack.groovy.Groovy.ratpack
import static ratpack.jackson.Jackson.json
def getServerRules() {
[
[path: "", response: "Hello world!"],
[path: "books", response: json([])],
[path: "books/42", response: json([title: "this is a mock"])],
[path: "books/42/reviews", response: json([])],
]
}
ratpack {
handlers {
getServerRules().each { rule ->
get(rule.path) {
render(rule.response)
}
}
}
}
正如您所看到的,所有处理程序都在for-循环中定义,这些循环遍历预定义的服务器规则。值得一提的两件事:
ratpack.jackson.Jackson.json(body)
方法返回JSON响应包装您的响应正文,与我在示例中所做的相似curl localhost:5050
Hello World!
curl localhost:5050/books
[]
curl localhost:5050/books/42
{"title":"this is a mock"}
curl localhost:5050/books/42/reviews
[]
我希望它有所帮助。