我想使用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,以便为每个项目定义一个处理程序吗?
发布于 2017-11-07 09:38:56
您可以通过迭代定义的服务器规则列表来定义所有处理程序,如下所示:
@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)
}
}
}
}如您所见,所有处理程序都是在遍历预定义的服务器规则的每个循环中定义的。值得一提的有两件事:
ratpack.jackson.Jackson.json(body)方法包装响应体,类似于我在示例中所做的工作输出
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
[]希望能帮上忙。
https://stackoverflow.com/questions/47153581
复制相似问题