ballerina 学习二十 http/https
提供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的更多相关文章
- ballerina 学习二十八 快速grpc 服务开发
ballerina 的grpc 开发模型,对于开发者来说简单了好多,不是schema first 的方式,而是我们 只要编写简单的ballerina service 就可以了,proto 文件是自动帮 ...
- ballerina 学习二十九 数据库操作
ballerina 数据操作也是比较方便的,官方也我们提供了数据操作的抽象,但是我们还是依赖数据库驱动的. 数据库驱动还是jdbc模式的 项目准备 项目结构 ├── mysql_demo │ ├── ...
- ballerina 学习二十六 项目docker 部署&& 运行(二)
ballerina 从发布,到现在官方文档的更新也是很给力的,同时也有好多改进,越来越好用了 可以参考官方文档 https://ballerina.io/learn/by-guide/restful- ...
- ballerina 学习二十五 项目docker 部署&& 运行
ballerina 官方提供了docker 的runtime,还是比较方便的 基本项目创建 使用cli创建项目 按照提示操作就行 ballerina init -i 项目结构 添加了dockerfil ...
- ballerina 学习二十四 监控ballerina
ballerina 服务的监控还是比较方便的,以及集成了Prometheus Grafana Jaeger Elastic Stack 监控服务监控的集成 主要包含以下几个步骤 a. 安装docker ...
- ballerina 学习二十二 弹性服务
主要包含断路器模式,负载均衡模式,故障转移,重试 Circuit Breaker 参考代码 import ballerina/http; import ballerina/log; import ba ...
- Python3.5 学习二十二
回顾: 发送请求时:发送请求头和请求数据 request.META和request.request.body 响应请求时:响应头和响应返回数据 response.HEADER和response.bod ...
- ballerina 学习二十七 项目k8s部署&& 运行
ballerina k8s 部署和docker 都是同样的简单,编写service 添加注解就可以了 参考项目 https://ballerina.io/learn/by-guide/restful- ...
- Java开发学习(二十二)----Spring事务属性、事务传播行为
一.事务配置 上面这些属性都可以在@Transactional注解的参数上进行设置. readOnly:true只读事务,false读写事务,增删改要设为false,查询设为true. timeout ...
随机推荐
- uva1424
Traveling salesmen of nhn. (the prestigious Korean internet company) report their current location t ...
- cocos2dx 3.x 蒙板 遮罩 点击圆功能
//注册触摸 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); listener->onT ...
- 使用Sed和Awk实现批量文件的文本替换
摘要: 使用 Sed 完成文本替换操作任务是非常合适的.结合 find 命令,即可实现指定批量文件的文本替换.同时给出了Awk的解决方案作为对比. 问题 现在, 我要将一个原有Java项目中的一些包及 ...
- Python Missing parentheses in call to 'print'
原来是因为Python2.X和Python3.X不兼容. 我安装的是Python3.X,但是我试图运行的却是Python2.X 的代码. 所以上面的语法在python3中是错误的.在python3中, ...
- Python面试题之Python反射详解
0x00 前言 反射,可以理解为利用字符串的形式去对象中操作成员属性和方法 反射的这点特性让我联想到了exec函数,也是把利用字符串的形式去让Python解释器去执行命令 Python Version ...
- hdu 6299 Balanced Sequence(贪心)题解
题意:题意一开始不是很明白...就是他给你n个串,让你重新排列组合这n个串(每个串内部顺序不变),使得匹配的括号长度最大.注意,题目要求not necessary continuous,括号匹配不需要 ...
- Coursera SDN M1.2.1 SDN History: Programmable Networks 1
接上第二点 NOTE (2)active networks => Programmability in networks(1990s) Sturcture: What are active ne ...
- shell 按行读取文件
#!/bin/bash count= //赋值语句,不加空格 cat test | while read line //cat 命令的输出作为read命令的输入,read读到的值放在line中 do ...
- [QT]QApplication和QCoreApplication的用法
转自:http://www.tuicool.com/articles/qmI7Bf 故事的背景是这样的,我们在写QT程序的时候或者在开始写QT程序之前总会看到这样的语句 QApplication ap ...
- spark streaming 使用geoIP解析IP
1.首先将GEOIP放到服务器上,如,/opt/db/geo/GeoLite2-City.mmdb 2.新建scala sbt工程,测试是否可以顺利解析 import java.io.Fileimpo ...