【问题标题】:How can I do this redirection from ballerinalang?我怎样才能从 ballerinalang 进行这种重定向?
【发布时间】:2017-11-22 13:08:58
【问题描述】:

我在 ballerinalang 中实现了一个名为 https://localhost:9090/isValidUser 的 REST 端点。下面是我的代码

import ballerina.net.http;

@http:configuration {
    basePath:"/",
    httpsPort:9090,
    keyStoreFile:"${ballerina.home}/bre/security/wso2carbon.jks",
    keyStorePassword:"wso2carbon",
    certPassword:"wso2carbon",
    trustStoreFile:"${ballerina.home}/bre/security/client-truststore.jks",
    trustStorePassword:"wso2carbon"
}
service<http> authentication {
    @http:resourceConfig {
        methods:["POST"],
        path:"/isValidUser"
    }

    resource isValidUser (http:Request req, http:Response res) {
        println(req.getHeaders());
        res.send();

    }
}

现在我需要做的是,当我从浏览器调用该 URL 时,在我的服务中发生一些验证后,我需要将用户重定向到另一个名为 https://localhost:3000 的 URL。

那么我怎样才能从ballerinalang 进行这种重定向呢?

【问题讨论】:

    标签: redirect ballerina


    【解决方案1】:

    Ballerina 提供了流畅的 API 来进行重定向。请检查以下详细说明侦听器端点重定向的代码。

    service<http:Service> redirect1 bind {port:9090} {
        @http:ResourceConfig {
            methods:["GET"],
            path:"/"
        }
        redirect1 (endpoint client, http:Request req) {
            http:Response res = new;
            _ = client -> redirect(res, http:REDIRECT_TEMPORARY_REDIRECT_307,
                ["http://localhost:9093/redirect2"]);
        }
    }
    

    完整的例子可以在 Ballerina Redirects 找到

    【讨论】:

      【解决方案2】:

      在 Ballerina 中,您需要自己处理重定向,方法是设置必要的标头和状态代码。以下示例是如何在 Ballerina 中重定向的简单演示。 (注意:我在 Ballerina 0.95.2 中试过这个)

      import ballerina.net.http;
      
      @http:configuration {basePath:"/hello"}
      service<http> helloWorld {
      
          @http:resourceConfig {
              methods:["GET"],
              path:"/"
          }
          resource sayHello (http:Request request, http:Response response) {
              map qParams = request.getQueryParams();
              var name, _ = (string)qParams.name;
      
              if (isExistingUser(name)) {
                  response.setStringPayload("Hello Ballerina!");
              } else {
                  response.setHeader("Location", "http://localhost:9090/hello/newUser");
                  response.setStatusCode(302);
              }
      
              _ = response.send();
          }
      
          @http:resourceConfig {path:"/newUser"}
          resource newUser (http:Request request, http:Response response) {
              string msg = "New to Ballerina? Welcome!";
              response.setStringPayload(msg);
              _ = response.send();
          }
      }
      
      function isExistingUser (string name) (boolean) {
          return name == "Ballerina";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        • 2014-08-13
        • 2020-01-03
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多