Grails动态休息端点映射

时间:2019-04-20 00:46:34

标签: grails

在我的网址映射中,我定义了此映射:

"/$controller/$action?/$id?(.$format)?"{}

现在我要添加一组版本2服务。

例如: URI上的一项新服务:/api/myaction

并且我希望能够定义一个新端点/api/v2/myaction,其中 myaction 将映射到一个名为 myactionV2

的新动作。

2 个答案:

答案 0 :(得分:1)

有许多方法可以做到这一点,而最佳解决方案取决于您未包括在问题中的某些因素。这是最贴近问题和OP上面添加的注释的解决方案。

查看位于https://github.com/jeffbrown/javaheadendpoints的项目。

https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v1/ApiController.groovy

package demo.v1

class ApiController {
    static namespace = 'v1'

    def myaction() {
        render 'This request was handled by version 1 of the api'
    }
}

https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v2/ApiController.groovy

package demo.v2

class ApiController {
    static namespace = 'v2'

    def myaction() {
        render 'This request was handled by version 2 of the api'
    }
}

https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/demo/v3/ApiController.groovy

package demo.v3

class ApiController {
    static namespace = 'v3'

    def myaction() {
        render 'This request was handled by version 3 of the api'
    }
}

https://github.com/jeffbrown/javaheadendpoints/blob/47f41b3943422c3c9e44a08ac646ecb2046972d1/grails-app/controllers/javaheadendpoints/UrlMappings.groovy

package javaheadendpoints

class UrlMappings {

    static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/$controller/$namespace/$action/$id?(.$format)?" {
            // ...
        }

        "/"(view:"/index")
        "500"(view:'/error')
        "404"(view:'/notFound')
    }
}

发送请求会产生我认为的请求行为:

$ curl http://localhost:8080/api/v1/myaction
This request was handled by version 1 of the api
$ curl http://localhost:8080/api/v2/myaction
This request was handled by version 2 of the api
$ curl http://localhost:8080/api/v3/myaction
This request was handled by version 3 of the api

其他选项包括使用Version http标头,但是由于上面的某些措辞,我认为这并不是您想要的。

我希望有帮助。

答案 1 :(得分:-1)

不应该那样做,我建议的方法是分成两个控制器

/api1/myaction
/api2/myaction

或正在行动

/api/myaction1
/api/myaction2