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 ...
随机推荐
- uva11732 Trie转化
有40001 个单词每个单词长度不超过1000,每个两个单词之间都要比较求要比较次数 int strcmp(char *s,char *t){ int i; for(i = 0; s[i]==t[i] ...
- WdatePicker设置日期范围
设置 结束日期不超过当天日期:设置 开始日期不超过结束日期:设置 开始日期默认显示当月1日的日期,结束日期显示当天日期?<label>开始日期:</label><inpu ...
- java第七天
p38~p41: 1.可以通过import 一个自定义类库(或者网上下的)在java中使用c风格的输入输出方式. 2.忘记优先顺序时应该用括号明确规定计算顺序. 3.java的操作符不同于c++,几乎 ...
- Python3.x:使用PyMysql连接Mysql数据库
Python3.x:使用PyMysql连接Mysql数据库 Python3.x完全不向前兼容,导致Python2.x中可以正常使用的库,到了Python3就用不了: 比如说mysqldb,目前MySQ ...
- 学习Zookeeper之第3章Zookeeper内部原理
第 3 章 Zookeeper 内部原理 3.1 选举机制 3.2 节点类型 3.3 stat 结构体 3.4 监听器原理 1)监听原理详解 2)常见的监听 3.5 写数据流程 第 3 章 Z ...
- 《Effective Java 2nd》第8章 通用程序设计
目录 第45条 将局部变量的作用域最小化 第46条 for-each循环优先于传统的for循环 第47条 了解和使用类库 第48条 如果需要精确的答案,避免使用float和double 第49条 基本 ...
- omnibus gitlab-ce安装
架构 关闭防火墙 [root@gitlab ~]# systemctl stop firewalld [root@gitlab ~]# systemctl disable firewalld 关闭SE ...
- thinkphp3.2笔记(2)调试模式,配置项C,创建模块, 四种URL模式,URL生成,跳转
一.调试模式 TP的调试模式其实就控制了TP关于配置信息以及函数的缓存功能 如果开启了调试模式,每次访问项目,Tp都会去加载最新的配置以及函数信息. 如果关闭了调试模式,当tp第一次访问时会降配置以及 ...
- [转]vim 退格键(backspace)不能用
http://my.oschina.net/zhangdapeng89/blog/56593 1.去掉讨厌的有关vi一致性模式,避免以前版本的一些bug和局限 set nocompatible ...
- JSP 生命周期
JSP 生命周期 理解JSP底层功能的关键就是去理解它们所遵守的生命周期. JSP生命周期就是从创建到销毁的整个过程,类似于servlet生命周期,区别在于JSP生命周期还包括将JSP文件编译成ser ...