The __Serve
function is used to create Http service, TCP service, and Websocket service (based on Http protocol).
Returns a string that records the IP address and port of the created service. For example: 127.0.0.1:8088
, [::]:8089
.
string
__Serve(serveURI, handler) __Serve(serveURI, handler, …args)
The serveURI
parameter is used to configure the protocol, IP address, port and other settings of the service binding, such as http://0.0.0.0:8088?gzip=true
, that is, http://:8088?gzip=true
.
serveURI
parameter setting, such as tcp://127.0.0.1:6666?tls=true
; you can add certificates and private keys, such as tls=true&cert_pem=xxxx&cert_key_pem=xxxx
.serveURI
parameter settings, such as http://127.0.0.1:6666?gzip=true
; you can set compression settings: gzip=true
.
The serveURI
parameter is used for Https, such as https://127.0.0.1:6666?tls=true&gzip=true
; you can add cert_pem
and cert_key_pem
parameters to load the certificate.serveURI
true
string
The handler
parameter is used to pass in the routing processing function (Http protocol), message processing function (TCP protocol), and Stream processing function (Websocket).
The callback function passed in by the parameter handler
can define multiple parameters, the first parameter is the ctx object (context object).
handler
true
function
The actual parameter of the callback function passed as the parameter handler
. There may be multiple parameters arg
, for example:
__Serve("http://:8088", function(ctx, a, b, c) {
Log(`ctx.host():`, ctx.host(), ", a=", a, ", b=", b, ", c=", c)
}, 1, 2, 3)
The parameters 1
, 2
, 3
passed in when calling the __Serve()
function correspond to the parameters a
, b
, c
passed in the callback function.
arg false string, number, bool, object, array, function, null value and other types supported by the system
function main() {
let httpServer = __Serve("http://:8088?gzip=true", function (ctx) {
Log("http connect from: ", ctx.remoteAddr(), "->", ctx.localAddr())
let path = ctx.path()
if (path == "/") {
ctx.write(JSON.stringify({
path: ctx.path(),
method: ctx.method(),
headers: ctx.headers(),
cookie: ctx.header("Cookie"),
remote: ctx.remoteAddr(),
query: ctx.rawQuery()
}))
} else if (path == "/tickers") {
let ret = exchange.GetTickers()
if (!ret) {
ctx.setStatus(500)
ctx.write(GetLastError())
} else {
ctx.write(JSON.stringify(ret))
}
} else if (path == "/wss") {
if (ctx.upgrade("websocket")) { // upgrade to websocket
while (true) {
let r = ctx.read(10)
if (r == "") {
break
} else if (r) {
if (r == "ticker") {
ctx.write(JSON.stringify(exchange.GetTicker()))
} else {
ctx.write("not support")
}
}
}
Log("websocket closed", ctx.remoteAddr())
}
} else {
ctx.setStatus(404)
}
})
let echoServer = __Serve("tcp://:8089", function (ctx) {
Log("tcp connect from: ", ctx.remoteAddr(), "->", ctx.localAddr())
while (true) {
let d = ctx.read()
if (!d) {
break
}
ctx.write(d)
}
Log("connect closed")
})
Log("http serve on", httpServer, "tcp serve on", echoServer)
for (var i = 0; i < 5; i++) {
if (i == 2) {
// test Http
var retHttp = HttpQuery("http://127.0.0.1:8088?num=123&limit=100", {"debug": true})
Log("retHttp:", retHttp)
} else if (i == 3) {
// test TCP
var tcpConn = Dial("tcp://127.0.0.1:8089")
tcpConn.write("Hello TCP Server")
var retTCP = tcpConn.read()
Log("retTCP:", retTCP)
} else if (i == 4) {
// test Websocket
var wsConn = Dial("ws://127.0.0.1:8088/wss|compress=gzip")
wsConn.write("ticker")
var retWS = wsConn.read(1000)
Log("retWS:", retWS)
// no depth
wsConn.write("depth")
retWS = wsConn.read(1000)
Log("retWS:", retWS)
}
Sleep(1000)
}
}
# Unsupported
// Unsupported
Websocket
service is implemented based on the Http protocol. You can set a routing branch in the path and design the implementation code for Websocket
message subscription/push. You can refer to the sample code in this section.The callback function passed in by the parameter handler
receives a ctx
parameter. The ctx
parameter is a context object used to get and write data, with the following methods:
- ctx.proto()
Applied to Http/TCP protocol, returns the protocol name when called. For example: HTTP/1.1
, tcp
.
- ctx.host()
Applied to Http protocol, it returns host information when called IP address and port.
- ctx.path()
Applied to the Http protocol, returns the request path when called.
- ctx.query(key)
Applied to Http protocol, returns the value corresponding to the key in the query in the request when called. For example, the request sent is: http://127.0.0.1:8088?num=123
, and the callback processing function passed in by the parameter handler
returns "123"
when ctx.query("num")
is called.
- ctx.rawQuery()
Applied to the Http protocol, when called, returns the original query in the request (the query of the Http request).
- ctx.headers()
Applied to the Http protocol, and returns the request header information in the request when called.
- ctx.header(key)
Applied to Http protocol, it returns the value of a key in the specified request header when called. For example, get the User-Agent
in the headers of the current request: ctx.header("User-Agent")
.
- ctx.method()
Applied to the Http protocol, returns the request method when called, such as GET
, POST
, etc.
- ctx.body()
Applied to POST request of Http protocol, and returns the body of the request when called.
- ctx.setHeader(key, value)
Applied to the Http protocol to set the request header information of the response message.
- ctx.setStatus(code)
Applied to Http protocol, set Http message status code. Usually, Http status code is set at the end of the routing branch. The default value is 200.
- ctx.remoteAddr()
Applied to Http/TCP protocol, returns the remote client address and port in the request when called.
- ctx.localAddr()
Applied to Http/TCP protocol, returns the local address and port of the service when called.
- ctx.upgrade(“websocket”)
Applied to the Websocket protocol implementation based on the Http protocol, switching the ctx
context object to the Websocket protocol; returning a Boolean value (true) if the switch is successful, and a Boolean value (false) if it fails.
- ctx.read(timeout_ms)
Applied to Websocket protocol implementation/TCP protocol based on Http protocol, reads data of Websocket connection and TCP connection. The read
method is not supported in ordinary Http protocol. You can specify the timeout parameter timeout_ms
in milliseconds.
- ctx.write(s)
Applied to Http/TCP protocol, used to write string data. You can use JSON.stringify()
to encode the JSON object into a string and then write it. For the WebSocket
protocol, you can use this method to pass the encoded string to the client.
{@fun/Global/HttpQuery HttpQuery}, {@fun/Global/HttpQuery_Go HttpQuery_Go}
EventLoop _G