【问题标题】:How to send custom http response code back from spring cloud functions in gcp?如何从gcp中的spring cloud函数发回自定义http响应代码?
【发布时间】:2020-09-08 11:52:54
【问题描述】:

我们正在使用 Java / Kotlin 的新 gcp 云功能。

在当前的参考实现中,我们返回 org.springframework.messaging.support.GenericMessage 对象。

所以我们的代码看起来像这样(Kotlin):

   fun generatePdfInBase64(message: Message<Map<String, Any>>): Message<*> {
        val document = process(message)
        val encoded = Base64.getEncoder().encodeToString(document.document)
        return GenericMessage(encoded)
    }

我们无法找到任何方法在我们的消息中包含自定义 http 响应代码,例如201什么的。该函数在没有异常或500的情况下只响应200。

有人知道这样做的方法吗?

最好的祝福

安迪

【问题讨论】:

    标签: kotlin google-cloud-platform spring-cloud-function


    【解决方案1】:

    正如官方documentation 中提到的,HttpResponse 类有一个名为setStatusCode 的方法,您可以在其中设置状态编号以方便您

    例如:

     switch (request.getMethod()) {
          case "GET":
            response.setStatusCode(HttpURLConnection.HTTP_OK);
            writer.write("Hello world!");
            break;
        
    

    另一方面,GenericMessage 的constructor 接收作为参数的有效负载,因此我认为您可以创建一个 json 格式的字符串,并使用构造函数来创建具有您需要的状态响应的 GenericMessage 实例。

    如果您想了解更多关于状态码的信息,请查看document

    【讨论】:

    • 感谢您的回答。不过,我们没有找到任何方法将状态代码插入到构造函数 / GenericMessage 的标头中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2021-09-21
    • 2023-02-22
    • 2014-10-09
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多