分享一个通过 DSL 快速构建简单 HTTP Server 的命令行工具

2019-11-18 09:36:01 +08:00
 kingddc314

https://github.com/six-ddc/mirage

一个基于 DSL 的快速构建简单的 HTTP Server 的命令行工具

特点

使用场景

示例

hello world

mirage -c 'get("/hello") { resp.println "world!"}'
# curl http://127.0.0.1:8080/hello
# world!

static file server

mirage -c 'get("/files/**") { resp.index "." }'
# curl http://127.0.0.1:8080/files/pom.xml

mock data

handle path: '/user/{uid}/get', method: "GET", {

    sleep 100.millisecond

    resp.json {
        id req.pathVariables.uid
        name random.forRegex(/[A-Z][a-z]{3,10}/)
        t new Date()
        data {
            contact 1..2, {
                id it
                name faker.name().name()
                address faker.address().fullAddress()
                phone faker.phoneNumber().cellPhone()
            }
        }
    }
}

get('/user/{uid}/get2') {

    // 或者基于模板语法直接编写 JSON response
    resp.eval """{
        "id": "${req.pathVariables.uid}",
        "name": "${random.forRegex(/[A-Z][a-z]{3,10}/)}",
        "t": "${new Date()}",
        "data": {
            "contact": [
                {
                    "id": 1,
                    "name": "${faker.name().name()}",
                    "address": "${faker.address().fullAddress()}",
                    "phone": "${faker.phoneNumber().cellPhone()}"
                },
                {
                    "id": 2,
                    "name": "${faker.name().name()}",
                    "address": "${faker.address().fullAddress()}",
                    "phone": "${faker.phoneNumber().cellPhone()}"
                }
            ]
        }
    }"""
}
mirage user.mir
$ curl -s http://127.0.0.1:8080/user/1234/get | jq .
$ curl -s http://127.0.0.1:8080/user/1234/get2 | jq .
{
  "id": "1234",
  "name": "Astn",
  "t": "2019-11-17T04:04:55+0000",
  "data": {
    "contact": [
      {
        "id": 1,
        "name": "Bryan Bashirian",
        "address": "22474 Bashirian Ways, New Thanhfurt, MA 32424-5437",
        "phone": "(973) 158-7100"
      },
      {
        "id": 2,
        "name": "Charley Jast",
        "address": "526 Corkery Rue, Lake Moises, MO 28747",
        "phone": "1-418-198-2865"
      }
    ]
  }
}

欢迎交流和体验使用:Github 地址

2852 次点击
所在节点    分享创造
1 条回复
zthxxx
2019-11-18 19:21:20 +08:00
一眼看成 Nginx

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/620519

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX