首页 > 解决方案 > 如何从gcp中的spring cloud函数发回自定义http响应代码?

问题描述

我们正在使用使用 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。

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

最好的祝愿

安迪

标签: kotlingoogle-cloud-platformspring-cloud-function

解决方案


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

例如:

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

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

如果您想了解更多关于 statuds 代码的信息,请查看此文档


推荐阅读