当前位置: 首页 > 工具软件 > dgate > 使用案例 >

dgate网关mock数据

苏承载
2023-12-01

dgate网关配置数据如下:

apiGateway1 {
    port = 7000
    login = "/login"
    urls {
        "/login" {
            required = ["sub", "password"]
            methods = [HttpMethod.GET, HttpMethod.POST]
            upstreamURLs = [
                [
                    host: 'localhost', port: 8080, url: '/login',
                    after: { simpleResponse ->
                        Map payload = [
                            sub: simpleResponse.payload.getString("sub"),
                            name: simpleResponse.payload.getString("name"),
                            role: simpleResponse.payload.getString("role")
                        ]
                        simpleResponse.payload.put('token', delegate.tokenGenerator.token(payload, 5))
                        simpleResponse
                    }
                ]
            ]
        }
        "/summary" {
            expected {
                statusCode = 200
                payload {
                    eqLocations = []
                    opRateInLast30Days = []
                    myOrgs = [
                        ["name": "org1", "admin": false]
                    ]
                }
            }
        }
        "/forward" {
            required = ['param1', 'param2']
            methods = ['GET', 'POST']
            upstreamURLs = [
                [host: 'localhost', port: 8080, url: '/test']
            ]
        }
        "/composite" {
            required = ['param1', 'param2']
            methods = ['GET', 'POST']
            upstreamURLs = [
                [host: 'localhost', port: 8080, url: '/test1'],
                [host: 'localhost', port: 8080, url: '/test2']
            ]
        }
    }
}

dgate网关支持mock模拟接口数据,上述配置中

 "/summary" {
            expected {
                statusCode = 200
                payload {
                    eqLocations = []
                    opRateInLast30Days = []
                    myOrgs = [
                        ["name": "org1", "admin": false]
                    ]
                }
            }
        }

即为mock数据,statusCode为响应状态码,payload为响应体内容。
对象中的key-value中间用=,没有用{}表示对象,通通用[]表示,如果表示json对象,配置 [“name”: “org1”, “admin”: false]即为{“name”: “org1”, “admin”: false}
如上述mock接口返回的数据为

{
    "eqLocations": [],
    "opRateInLast30Days": [],
    "myOrgs": [{
        "name": "org1",
        "admin": false
    }]
}

要想myOrgs对象为json对象,则修改配置如下

...
 "/summary" {
            expected {
                statusCode = 200
                payload {
                    eqLocations = []
                    opRateInLast30Days = []
                    myOrgs = [
                        "name": "org1", "admin": false
                    ]
                }
            }
        }
...

则接口返回的数据为

{
    "eqLocations": [],
    "opRateInLast30Days": [],
    "myOrgs": {
        "name": "org1",
        "admin": false
    }
}
 类似资料: