Ratpack:定义从列表中读取的路由



我想用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以便以某种方式为每个项目定义处理程序吗?

您可以通过迭代定义的服务器规则列表来定义所有处理程序,类似于以下 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
[]

我希望它有所帮助。

最新更新