提供http && https server && client 访问功能

client endpoint

说白了就是http client

  • 参考代码
import ballerina/http;
import ballerina/log;endpoint http:Client clientEndpoint {
url: "https://postman-echo.com"
};function main(string... args) { http:Request req = new;
var response = clientEndpoint->get("/get?test=123"); match response {
http:Response resp => {
log:printInfo("GET request:");
var msg = resp.getJsonPayload();
match msg {
json jsonPayload => {
log:printInfo(jsonPayload.toString());
}
error err => {
log:printError(err.message, err = err);
}
}
}
error err => { log:printError(err.message, err = err); }
}
req.setPayload("POST: Hello World"); response = clientEndpoint->post("/post", request = req);
match response {
http:Response resp => {
log:printInfo("\nPOST request:");
var msg = resp.getJsonPayload();
match msg {
json jsonPayload => {
log:printInfo(jsonPayload.toString());
}
error err => {
log:printError(err.message, err = err);
}
}
}
error err => { log:printError(err.message, err = err); } }
json jsonMsg = { method: "PUT", payload: "Hello World" };
req.setJsonPayload(jsonMsg); response = clientEndpoint->put("/put", request = req);
match response {
http:Response resp => {
log:printInfo("\nPUT request:");
var msg = resp.getJsonPayload();
match msg {
json jsonPayload => {
log:printInfo(jsonPayload.toString());
}
error err => {
log:printError(err.message, err = err);
}
}
}
error err => { log:printError(err.message, err = err); }
}
xml xmlMsg = xml `<request>
<method>PATCH</method>
<payload>Hello World!</payload>
</request>`;
req.setXmlPayload(xmlMsg); response = clientEndpoint->patch("/patch", request = req);
match response {
http:Response resp => {
log:printInfo("\nPATCH request:");
var msg = resp.getJsonPayload();
match msg {
json jsonPayload => {
log:printInfo(jsonPayload.toString());
}
error err => {
log:printError(err.message, err = err);
}
}
}
error err => { log:printError(err.message, err = err); }
} req.setPayload("DELETE: Hello World");
response = clientEndpoint->delete("/delete", request = req);
match response {
http:Response resp => {
log:printInfo("\nDELETE request:");
var msg = resp.getJsonPayload();
match msg {
json jsonPayload => {
log:printInfo(jsonPayload.toString());
}
error err => {
log:printError(err.message, err = err);
}
}
}
error err => { log:printError(err.message, err = err); }
} req.setPayload("CUSTOM: Hello World");
response = clientEndpoint->execute("COPY", "/get", req); req = new;
req.addHeader("Sample-Name", "http-client-connector");
response = clientEndpoint->get("/get", request = req);
match response {
http:Response resp => {
string contentType = resp.getHeader("Content-Type");
log:printInfo("\nContent-Type: " + contentType); int statusCode = resp.statusCode;
log:printInfo("Status code: " + statusCode); }
error err => { log:printError(err.message, err = err); }
}
}
  • 输出结果
2018-06-01 21:03:32,032 INFO [] - GET request:
2018-06-01 21:03:32,059 INFO [] - {"args":{"test":"123"},"headers":{"host":"postman-echo.com","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"url":"https://postman-echo.com/get?test=123"}
2018-06-01 21:03:32,633 INFO [] -
POST request:
2018-06-01 21:03:32,636 INFO [] - {"args":{},"data":"POST: Hello World","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"17","content-type":"text/plain","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/post"}
2018-06-01 21:03:33,349 INFO [] -
PUT request:
2018-06-01 21:03:33,351 INFO [] - {"args":{},"data":{"method":"PUT","payload":"Hello World"},"files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"40","content-type":"application/json","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":{"method":"PUT","payload":"Hello World"},"url":"https://postman-echo.com/put"}
2018-06-01 21:03:33,861 INFO [] -
PATCH request:
2018-06-01 21:03:33,863 INFO [] - {"args":{},"data":"<request>\n <method>PATCH<\/method>\n <payload>Hello World!<\/payload>\n <\/request>","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"145","content-type":"application/xml","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/patch"}
2018-06-01 21:03:34,373 INFO [] -
DELETE request:
2018-06-01 21:03:34,375 INFO [] - {"args":{},"data":"DELETE: Hello World","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"19","content-type":"text/plain","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/delete"}
2018-06-01 21:03:35,193 INFO [] -
Content-Type: application/json; charset=utf-8
2018-06-01 21:03:35,193 INFO [] - Status code: 200

http client redirect

redirect 是服务器端的相应,一般http 客户端不会进行处理,ballerina 有可选的配置参数,同时可以设置最大次数(防止死循环)

  • 参考代码
import ballerina/io;
import ballerina/http;
import ballerina/log;
import ballerina/mime;endpoint http:Client clientEP {
url: "http://localhost:9090",
followRedirects: { enabled: true, maxCount: 5 }
};
function main(string... args) {
var returnResult = clientEP->get("/redirect1"); match returnResult {
error connectionErr => log:printError("Error in connection",
err = connectionErr);
http:Response resp => {
match resp.getTextPayload() {
error e => log:printError("Error in payload", err = e);
string payload => io:println("Response received : " + payload);
}
}
}
}
@http:ServiceConfig {
basePath:"/redirect1"
}
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"]);
}
}@http:ServiceConfig {
basePath:"/redirect2"
}
service<http:Service> redirect2 bind {port:9093} { @http:ResourceConfig {
methods:["GET"],
path:"/"
}
redirect2 (endpoint client, http:Request req) {
http:Response res = new;
res. setPayload("Hello World!");
_ = client -> respond( res) but { error e => log:printError("Error in
responding", err = e) };
}
}

## http server base path && params

  • 参考代码
import ballerina/http;
import ballerina/log;
import ballerina/mime;
@http:ServiceConfig { basePath: "/foo" }
service<http:Service> echo bind { port: 9090 } {
@http:ResourceConfig {
methods: ["POST"],
path: "/bar"
}
echo(endpoint caller, http:Request req) {
var result = req.getJsonPayload();
http:Response res = new;
match result {
error err => {
res.statusCode = 500;
res.setPayload(err.message);
}
json value => {
res.setJsonPayload(value);
}
}
caller->respond(res) but {
error e => log:printError("Error in responding", err = e)
};
}
} import ballerina/http;
import ballerina/log;@http:ServiceConfig
service<http:Service> sample bind { port: 9090 } { @http:ResourceConfig {
methods: ["GET"],
path: "/path/{foo}"
}
params(endpoint caller, http:Request req, string foo) {
var params = req.getQueryParams();
var bar = <string>params.bar;
map pathMParams = req.getMatrixParams("/sample/path");
var a = <string>pathMParams.a;
var b = <string>pathMParams.b;
string pathMatrixStr = string `a={{a}}, b={{b}}`;
map fooMParams = req.getMatrixParams("/sample/path/" + foo);
var x = <string>fooMParams.x;
var y = <string>fooMParams.y;
string fooMatrixStr = string `x={{x}}, y={{y}}`;
json matrixJson = { "path": pathMatrixStr, "foo": fooMatrixStr };
json responseJson = { "pathParam": foo, "queryParam": bar, "matrix": matrixJson };
http:Response res = new;
res.setJsonPayload(responseJson);
caller->respond(res) but { error e => log:printError("Error when responding", err = e) };
}
}

https server

  • 参考代码
import ballerina/http;
import ballerina/log;
endpoint http:Listener helloWorldEP {
port: 9095,
secureSocket: {
keyStore: {
path: "${ballerina.home}/bre/security/ballerinaKeystore.p12",
password: "ballerina"
}
}
};
@http:ServiceConfig {
basePath: "/hello"
}
service helloWorld bind helloWorldEP {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
sayHello(endpoint caller, http:Request req) {
http:Response res = new;
res.setPayload("Hello World!");
caller->respond(res) but {
error e => log:printError("Error in responding ", err = e) };
}
}

cors

一般进行跨域处理

  • 参考代码
import ballerina/http;
import ballerina/log;
@http:ServiceConfig {
cors: {
allowOrigins: ["http://www.m3.com", "http://www.hello.com"],
allowCredentials: false,
allowHeaders: ["CORELATION_ID"],
exposeHeaders: ["X-CUSTOM-HEADER"],
maxAge: 84900
}
}
service<http:Service> crossOriginService bind { port: 9092 } { string respErr = "Failed to respond to the caller";
@http:ResourceConfig {
methods: ["GET"],
path: "/company",
cors: {
allowOrigins: ["http://www.bbc.com"],
allowCredentials: true,
allowHeaders: ["X-Content-Type-Options", "X-PINGOTHER"]
}
}
companyInfo(endpoint caller, http:Request req) {
http:Response res = new;
json responseJson = { "type": "middleware" };
res.setJsonPayload(responseJson);
caller->respond(res) but { error e => log:printError(respErr, err = e) };
}
@http:ResourceConfig {
methods: ["POST"],
path: "/lang"
}
langInfo(endpoint caller, http:Request req) {
http:Response res = new;
json responseJson = { "lang": "Ballerina" };
res.setJsonPayload(responseJson);
caller->respond(res) but { error e => log:printError(respErr, err = e) };
}
}

数据绑定

http body 序列化

  • 参考代码
import ballerina/http;
import ballerina/io;
import ballerina/log;type Student {
string Name;
int Grade;
map Marks;
};
@http:ServiceConfig
service<http:Service> hello bind { port: 9090 } { string respErr = "Failed to respond to the caller";
@http:ResourceConfig {
methods: ["POST"],
body: "orderDetails"
}
bindJson(endpoint caller, http:Request req, json orderDetails) {
json details = orderDetails.Details; http:Response res = new;
res.setPayload(details);
caller->respond(res) but { error e => log:printError(respErr, err = e) };
}
@http:ResourceConfig {
methods: ["POST"],
body: "store",
consumes: ["application/xml"]
}
bindXML(endpoint caller, http:Request req, xml store) {
xml city = store.selectDescendants("{http://www.test.com}city"); http:Response res = new;
res.setPayload(city);
caller->respond(res) but { error e => log:printError(respErr, err = e) };
}
@http:ResourceConfig {
methods: ["POST"],
body: "student",
consumes: ["application/json"]
}
bindStruct(endpoint caller, http:Request req, Student student) {
string name = student.Name; int grade = student.Grade; http:Response res = new;
res.setPayload({ Name: name, Grade: grade });
caller->respond(res) but { error e => log:printError(respErr, err = e) };
}
}

参考资料

https://ballerina.io/learn/by-example/http-client-endpoint.html
https://ballerina.io/learn/by-example/https-listener.html
https://ballerina.io/learn/by-example/http-cors.html
https://ballerina.io/learn/by-example/http-data-binding.html

 
 
 
 

ballerina 学习二十 http/https的更多相关文章

  1. ballerina 学习二十八 快速grpc 服务开发

    ballerina 的grpc 开发模型,对于开发者来说简单了好多,不是schema first 的方式,而是我们 只要编写简单的ballerina service 就可以了,proto 文件是自动帮 ...

  2. ballerina 学习二十九 数据库操作

    ballerina 数据操作也是比较方便的,官方也我们提供了数据操作的抽象,但是我们还是依赖数据库驱动的. 数据库驱动还是jdbc模式的 项目准备 项目结构 ├── mysql_demo │ ├── ...

  3. ballerina 学习二十六 项目docker 部署&& 运行(二)

    ballerina 从发布,到现在官方文档的更新也是很给力的,同时也有好多改进,越来越好用了 可以参考官方文档 https://ballerina.io/learn/by-guide/restful- ...

  4. ballerina 学习二十五 项目docker 部署&& 运行

    ballerina 官方提供了docker 的runtime,还是比较方便的 基本项目创建 使用cli创建项目 按照提示操作就行 ballerina init -i 项目结构 添加了dockerfil ...

  5. ballerina 学习二十四 监控ballerina

    ballerina 服务的监控还是比较方便的,以及集成了Prometheus Grafana Jaeger Elastic Stack 监控服务监控的集成 主要包含以下几个步骤 a. 安装docker ...

  6. ballerina 学习二十二 弹性服务

    主要包含断路器模式,负载均衡模式,故障转移,重试 Circuit Breaker 参考代码 import ballerina/http; import ballerina/log; import ba ...

  7. Python3.5 学习二十二

    回顾: 发送请求时:发送请求头和请求数据 request.META和request.request.body 响应请求时:响应头和响应返回数据 response.HEADER和response.bod ...

  8. ballerina 学习二十七 项目k8s部署&& 运行

    ballerina k8s 部署和docker 都是同样的简单,编写service 添加注解就可以了 参考项目 https://ballerina.io/learn/by-guide/restful- ...

  9. Java开发学习(二十二)----Spring事务属性、事务传播行为

    一.事务配置 上面这些属性都可以在@Transactional注解的参数上进行设置. readOnly:true只读事务,false读写事务,增删改要设为false,查询设为true. timeout ...

随机推荐

  1. acdream1174 合并同类项

    这题说的是 给出N,a[1]... a[N],还有M,b[1]... b[M]long long ans = 0;for(int i = 1; i <= N; i ++)    for(int ...

  2. Python 以指定列宽格式化字符串

    问题: 有一些长字符串,想以指定的列宽将他们重新格式化 解决方案: 使用textwrap模块来格式字符串的输出. textwrap 模块对于字符串打印时非常有用的,特别是当希望输出自动匹配终端大小的时 ...

  3. Ruby 安装和gem配置

    在linux或mac等*unix系统下可以使用rvm来进行ruby的配置和管理. 安装方法 (需要curl) curl -L get.rvm.io | bash -s stable rvm官方网站: ...

  4. 前端面试题之 sum(2)(3) (链式调用,toString,柯里化,数组操作)

    写一个函数让下面两个输出结果相同:console.log(sum(2)(3));console.log(sum(2,3)); var sum = (function() { var list = [] ...

  5. 《Java入门第二季》第一章 类和对象

    什么是类和对象 如何定义 Java 中的类 如何使用 Java 中的对象 Java中的成员变量和局部变量1.成员变量:在类中定义,描述构成对象的组件. 2.局部变量:在类的方法中,用于临时保存数据. ...

  6. Django:表结构发生变化需要执行命令

    Django:表结构发生变化需要执行命令 Django:表结构发生变化需要执行命令 mysite> python manage.py makemigrations blog #让 Django ...

  7. 实验四——使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

    实验目的: 使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用 实验过程: 查看系统调用列表 get pid 函数 #include <stdio.h> #include & ...

  8. Linux基础入门(实验楼实验)

    实验一 Linux系统简介 Linux和windows.Mac OS一样是一种操作系统.最早流行起来的操作系统是UNIX,但由于其过度商业化,价格昂贵,因此在校园里人们大多选择MINIX.1991年, ...

  9. Codeforces Round #408 (Div. 2) C. Bank Hacking

    http://codeforces.com/contest/796/problem/C Although Inzane successfully found his beloved bone, Zan ...

  10. git 撤销

    在add之前撤回文件: git checkout src/com/jay/example/testforgit/MainActivity.java 已经add的,先取消添加,再撤回 git reset ...