Как передать необязательные параметры запроса с groovy? - PullRequest
0 голосов
/ 23 марта 2020

Я хотел бы передать необязательные параметры в URL, используя micronaut с groovy. Я провел много исследований, но не смог найти никакого соответствующего ответа.

@Get('/product/{country}/?

Я хотел бы передать сортировку и дату в качестве необязательных параметров для этого URL. Ценю твою помощь.

1 Ответ

3 голосов
/ 23 марта 2020

Вы можете передавать необязательные параметры сортировки и даты в качестве значений запроса, например:

@Controller('/')
@CompileStatic
class WithOptionalParameterController {
    @Get('/product/{country}{?sort,date}')
    String productsForCountry(String country, 
                              @Nullable @Pattern(regexp = 'code|title') String sort, 
                              @Nullable String date) {
        "Products for $country sorted by $sort and there is also date $date."
    }
}

И его можно вызывать так, указав сортировку и дату:

$ curl 'http://localhost:8080/product/chile?sort=code&date=23.3.2020'
Products for chile sorted by code and there is also date 23.3.2020.

Или без дата:

$ curl 'http://localhost:8080/product/chile?sort=code'
Products for chile sorted by code and there is also date null.

или без сортировки и даты:

$ curl 'http://localhost:8080/product/chile'
Products for chile sorted by null and there is also date null.

Пример для POST, где необходимо добавить @QueryValue аннотацию для параметров запроса:

@Consumes([MediaType.TEXT_PLAIN])
@Post('/product/{country}{?sort,date}')
String productsForCountry(String country, 
                          @Nullable @Pattern(regexp = 'code|title') @QueryValue String sort,
                          @Nullable @QueryValue String date,
                          @Body String body) {
    "Products for $country sorted by $sort and there is also date $date. Body is $body."
}

И это можно назвать так:

$ curl -X POST 'http://localhost:8080/product/chile?sort=code&date=23.3.2020' -H "Content-Type: text/plain" -d 'some body'
Products for chile sorted by code and there is also date 23.3.2020. Body is some body.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...