我想使用 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 ??? )
}
}
}
}
我可以迭代这些规则
以便以某种方式为每个项目定义一个处理程序吗?
最佳答案
您可以通过迭代已定义的服务器规则列表来定义所有处理程序,如以下 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-each 循环内定义的,该循环迭代预定义的服务器规则。有两件事值得一提:
- 请勿以“/”开头的 URL 路径,否则无法定义端点
- 如果您想返回 JSON 响应,请使用
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
[]
希望对您有所帮助。
关于groovy - Ratpack:定义从列表中读取的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153581/