skynet源码分析(16)--skynet中http之httpc和httpd

作者:shihuaping0918@163.com,转载请注明作者

httpc.lua和httpd.lua提供的功能比较简陋,函数也比较少,代码量比较少,一百多行。在对http协议有一定认识的前提下,分析这两个文件的代码是比较简单的。

httpc.lua是http客户端代码,支持get/post请求,发送完请求以后等待回应。并解析回应包。

local skynet = require "skynet"
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local dns = require "skynet.dns"
local string = string
local table = table

local httpc = {}
--发送请求并等待回应
local function request(fd, method, host, url, recvheader, header, content)
    local read = socket.readfunc(fd)
    local write = socket.writefunc(fd)
    local header_content = ""
    if header then
        if not header.host then
            header.host = host
        end
        for k,v in pairs(header) do --http头组成字符串
            header_content = string.format("%s%s:%s\r\n", header_content, k, v)
        end
    else
        header_content = string.format("host:%s\r\n",host)
    end

    if content then --有消息体
        local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n", method, url, header_content, #content) 
--content-length为消息体长度
        write(data)
        write(content)
    else --无消息体
        local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content)
--content-length为消息体长度,没有消息体就为0
        write(request_header)
    end
--等待回应
    local tmpline = {}
    local body = internal.recvheader(read, tmpline, "")
    if not body then
        error(socket.socket_error)
    end
--取出状态码,200是ok
    local statusline = tmpline[1]
    local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
    code = assert(tonumber(code))
--取消息头
    local header = internal.parseheader(tmpline,2,recvheader or {})
    if not header then
        error("Invalid HTTP response header")
    end
--取content-length
    local length = header["content-length"]
    if length then
        length = tonumber(length)
    end
--取消息体编码方式
    local mode = header["transfer-encoding"]
    if mode then
        if mode ~= "identity" and mode ~= "chunked" then
            error ("Unsupport transfer-encoding")
        end
    end
--读取消息体
    if mode == "chunked" then
        body, header = internal.recvchunkedbody(read, nil, header, body)
        if not body then
            error("Invalid response body")
        end
    else
        -- identity mode
        if length then
            if #body >= length then
                body = body:sub(1,length)
            else
                local padding = read(length - #body)
                body = body .. padding
            end
        else
            -- no content-length, read all
            body = body .. socket.readall(fd)
        end
    end

    return code, body
end

local async_dns

function httpc.dns(server,port)
    async_dns = true
    dns.server(server,port)
end

function httpc.request(method, host, url, recvheader, header, content)
    local timeout = httpc.timeout   -- get httpc.timeout before any blocked api
    local hostname, port = host:match"([^:]+):?(%d*)$"
    if port == "" then --默认端口80
        port = 80
    else
        port = tonumber(port)
    end
--如果是域名,而不是ip
    if async_dns and not hostname:match(".*%d+$") then
        hostname = dns.resolve(hostname)
    end
--连接服务器,如果timeout>0,就是异步等待
    local fd = socket.connect(hostname, port, timeout)
    local finish
    if timeout then
        skynet.timeout(timeout, function()
            if not finish then
                socket.shutdown(fd) -- shutdown the socket fd, need close later.
            end
        end)
    end
--调用上面定义的request函数,在保护模式下进行
    local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content)
    finish = true
    socket.close(fd)
    if ok then
        return statuscode, body
    else
        error(statuscode)
    end
end
--get方法
function httpc.get(...)
    return httpc.request("GET", ...)
end
--转换为百分号表示
local function escape(s)
    return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
        return string.format("%%%02X", string.byte(c))
    end))
end
--post方法
function httpc.post(host, url, form, recvheader)
    local header = {
        ["content-type"] = "application/x-www-form-urlencoded"
    }
    local body = {}
    for k,v in pairs(form) do
        table.insert(body, string.format("%s=%s",escape(k),escape(v)))
    end

    return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end

return httpc

httpd.lua,功能只有读取请求,解析请求。发送回应。

local internal = require "http.internal"

local table = table
local string = string
local type = type

local httpd = {}
--错误状态码定义
local http_status_msg = {
    [100] = "Continue",
    [101] = "Switching Protocols",
    [200] = "OK",
    [201] = "Created",
    [202] = "Accepted",
    [203] = "Non-Authoritative Information",
    [204] = "No Content",
    [205] = "Reset Content",
    [206] = "Partial Content",
    [300] = "Multiple Choices",
    [301] = "Moved Permanently",
    [302] = "Found",
    [303] = "See Other",
    [304] = "Not Modified",
    [305] = "Use Proxy",
    [307] = "Temporary Redirect",
    [400] = "Bad Request",
    [401] = "Unauthorized",
    [402] = "Payment Required",
    [403] = "Forbidden",
    [404] = "Not Found",
    [405] = "Method Not Allowed",
    [406] = "Not Acceptable",
    [407] = "Proxy Authentication Required",
    [408] = "Request Time-out",
    [409] = "Conflict",
    [410] = "Gone",
    [411] = "Length Required",
    [412] = "Precondition Failed",
    [413] = "Request Entity Too Large",
    [414] = "Request-URI Too Large",
    [415] = "Unsupported Media Type",
    [416] = "Requested range not satisfiable",
    [417] = "Expectation Failed",
    [500] = "Internal Server Error",
    [501] = "Not Implemented",
    [502] = "Bad Gateway",
    [503] = "Service Unavailable",
    [504] = "Gateway Time-out",
    [505] = "HTTP Version not supported",
}
--读请求
local function readall(readbytes, bodylimit)
    local tmpline = {}
    local body = internal.recvheader(readbytes, tmpline, "")
    if not body then
        return 413  -- Request Entity Too Large
    end
    local request = assert(tmpline[1])
    --请求url/method,http版本号,start line对应的内容
    local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$"
    assert(method and url and httpver)
    httpver = assert(tonumber(httpver))
    if httpver < 1.0 or httpver > 1.1 then --http版本错误
        return 505  -- HTTP Version not supported
    end
    local header = internal.parseheader(tmpline,2,{})
    if not header then
        return 400  -- Bad request
    end
    local length = header["content-length"] --消息体长度,所有的field name被转成小写了
    if length then
        length = tonumber(length)
    end
    local mode = header["transfer-encoding"] --消息体编码格式
    if mode then
        if mode ~= "identity" and mode ~= "chunked" then
            return 501  -- Not Implemented
        end
    end

    if mode == "chunked" then --chunked方式
        body, header = internal.recvchunkedbody(readbytes, bodylimit, header, body)
        if not body then
            return 413
        end
    else
        -- identity mode
        if length then
            if bodylimit and length > bodylimit then
                return 413
            end
            if #body >= length then
                body = body:sub(1,length)
            else
                local padding = readbytes(length - #body) --读指定的长度
                body = body .. padding 
            end
        end
    end

    return 200, url, method, header, body
end
--读取http请求
function httpd.read_request(...)
    local ok, code, url, method, header, body = pcall(readall, ...)
    if ok then
        return code, url, method, header, body
    else
        return nil, code
    end
end
--发应答包
local function writeall(writefunc, statuscode, bodyfunc, header)
     --http start line
    local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "")
    writefunc(statusline)
    if header then --发http头
        for k,v in pairs(header) do
            if type(v) == "table" then --表中表,或者表中key对应的是数组
                for _,v in ipairs(v) do
                    writefunc(string.format("%s: %s\r\n", k,v))
                end
            else
                writefunc(string.format("%s: %s\r\n", k,v))
            end
        end
    end
    local t = type(bodyfunc) --wtf,这个名字取得很误导
    if t == "string" then
        writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) --消息体长度
        writefunc(bodyfunc) --bodyfunc是字符串啊,所以说名字取得很误导人
    elseif t == "function" then
        writefunc("transfer-encoding: chunked\r\n")
        while true do
            local s = bodyfunc() --取消息体的一部分,应该是个generator才对
            if s then
                if s ~= "" then
                    writefunc(string.format("\r\n%x\r\n", #s)) --chunk size
                    writefunc(s) --chunk data
                end
            else
                writefunc("\r\n0\r\n\r\n") --last chunk
                break
            end
        end
    else
        assert(t == "nil")
        writefunc("\r\n")
    end
end

function httpd.write_response(...)
    return pcall(writeall, ...)
end

return httpd

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容