请检查 Ballerina 中定义的以下服务类别。
service class RequestInterceptor {
*http:RequestInterceptor;
// A default resource function, which will be executed for all the requests.
// A `RequestContext` is used to share data between the interceptors.
// An accessor and a path can also be specified. In that case, the interceptor will be
// executed only for the requests, which match the accessor and path.
resource function 'default [string... path](http:RequestContext ctx,
http:Request req) returns http:NextService|error? {
// Sets a header to the request inside the interceptor service.
req.setHeader(interceptor_header, interceptor_header_value);
// Returns the next interceptor or the target service in the pipeline.
// An error is returned when the call fails.
return ctx.next();
}
}
在上面的服务类中,有一个从
*
开始的字段。 (即*http:RequestInterceptor;
)。
这种特殊的字段有什么用?
这是对象类型包含。它包括所包含类型中声明的字段和方法。
class Person {
string name;
function init(string name) {
self.name = name;
}
function getName() returns string {
return self.name;
}
}
class Employee {
// Includes `Person`.
// Therefore, `Employee` will also have the string field `name`
// and will have to initialize it.
// `Employee` will also have to implement the `getName` method.
*Person;
// Additional field.
string department;
function init(string name, string department) {
// `self.name` can be used as if the field was defined explicitly in `Employee`.
self.name = name;
self.department = department;
}
function getName() returns string {
return self.name.trim();
}
}
在这种特殊情况下,
RequestInterceptor
使用包含在RequestInterceptor
模块中定义的ballerina/http
不同对象类型。这使得 RequestInterceptor
成为 `http:RequestInterceptor. 的子类型。
另请参阅,
https://ballerina.io/learn/advanced-general- Purpose-language-features/#object-type-inclusion,
https://ballerina.io/learn/advanced-general- Purpose-language-features/#distinct-object-types