├── .busted ├── .circleci └── config.yml ├── .codeclimate.yml ├── .gitignore ├── .luacheckrc ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── Roverfile ├── Roverfile.lock ├── benchmark └── split.lua ├── bin └── busted ├── dist.ini ├── rockspecs ├── lua-resty-url-0.3.3-1.rockspec ├── lua-resty-url-0.3.5-1.rockspec └── lua-resty-url-scm-1.rockspec ├── spec └── resty │ └── url_spec.lua └── src └── resty └── url.lua /.busted: -------------------------------------------------------------------------------- 1 | local ci = os.getenv('CI') 2 | 3 | if ci then 4 | return { 5 | default = { 6 | output = 'junit', 7 | Xoutput = 'tmp/junit/busted.xml', 8 | } 9 | } 10 | end 11 | 12 | return { } 13 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: quay.io/3scale/s2i-openresty-centos7:master 6 | working_directory: /opt/app-root/lua-resty-url 7 | steps: 8 | - checkout 9 | - restore_cache: 10 | keys: 11 | - resty-url-rover-{{ arch }}-{{ checksum "Roverfile.lock" }} 12 | - resty-url-rover-{{ arch }}-{{ .Branch }} 13 | - resty-url-rover-{{ arch }}-master 14 | - run: mkdir -p tmp/junit; rover install 15 | - save_cache: 16 | key: resty-url-rover-{{ arch }}-{{ checksum "Roverfile.lock" }} 17 | paths: 18 | - lua_modules 19 | - run: busted 20 | - store_artifacts: 21 | path: tmp 22 | destination: tmp 23 | - store_test_results: 24 | path: tmp/junit 25 | -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | --- 2 | engines: 3 | fixme: 4 | enabled: true 5 | luacheck: 6 | enabled: true 7 | channel: beta 8 | ratings: 9 | paths: 10 | - "**/*.lua" 11 | exclude_paths: 12 | - .idea 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /lua-resty-*-* 2 | !*.rockspec 3 | lua_modules 4 | -------------------------------------------------------------------------------- /.luacheckrc: -------------------------------------------------------------------------------- 1 | std = 'ngx_lua+lua52' -- lua52 has table.pack 2 | 3 | files["spec"] = {std = "+busted"} 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | ## Unreleased 8 | 9 | ### Fixed 10 | 11 | ## [0.3.5] - 2019-05-21 12 | 13 | ### Fixed 14 | * Parsing URLs with uppercase characters 15 | 16 | ## [0.3.4] - 2018-11-27 17 | 18 | ### Fixed 19 | * Parsing Lua 5.1 compatibility 20 | 21 | ## [0.3.3] - 2018-07-31 22 | 23 | ### Fixed 24 | * Parsing URLs with underscores in domain 25 | 26 | ## [0.3.2] - 2018-07-20 27 | 28 | ### Fixed 29 | * Parsing URLs with numbers in host 30 | 31 | ## [0.3.1] - 2018-07-19 32 | 33 | ### Fixed 34 | * Parsing URLs with numbers in host 35 | 36 | ## [0.3.0] - 2018-07-19 37 | 38 | ### Added 39 | * Support for data-uri 40 | 41 | ## Changed 42 | * Significantly improve performance 43 | 44 | ## [0.2.0] - 2017-07-12 45 | 46 | ### Added 47 | * `resty_url.normalize(url)` to normalize multiple slashes 48 | * `resty_url.join(...)` to join parsed urls and perform normalization 49 | 50 | ## [0.1.0] - 2017-07-04 51 | 52 | Initial release. 53 | 54 | [0.1.0]: https://github.com/3scale/lua-resty-url/commit/v0.1.0 55 | [0.2.0]: https://github.com/3scale/lua-resty-url/commit/v0.2.0 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | Roverfile.lock: Roverfile 3 | rover lock 4 | 5 | lua_modules: Roverfile.lock Roverfile 6 | rover install 7 | 8 | test: 9 | @resty -e "require('busted.runner')({ standalone = false })" 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | lua-resty-url [![CircleCI](https://circleci.com/gh/3scale/lua-resty-url.svg?style=svg)](https://circleci.com/gh/3scale/lua-resty-url) 2 | ==== 3 | 4 | lua-resty-url - URL parser for OpenResty. 5 | 6 | 7 | Table of Contents 8 | ================= 9 | 10 | * [Name](#name) 11 | * [Status](#status) 12 | * [Description](#description) 13 | * [Synopsis](#synopsis) 14 | * [Methods](#methods) 15 | * [get](#get) 16 | * [set](#set) 17 | * [value](#value) 18 | * [enabled](#enabled) 19 | * [reset](#reset) 20 | * [Installation](#installation) 21 | * [TODO](#todo) 22 | * [Community](#community) 23 | * [Bugs and Patches](#bugs-and-patches) 24 | * [Author](#author) 25 | * [Copyright and License](#copyright-and-license) 26 | * [See Also](#see-also) 27 | 28 | Status 29 | ====== 30 | 31 | This library is considered production ready. 32 | 33 | Description 34 | =========== 35 | 36 | This Lua library is very simple Regex based URL parser. 37 | 38 | This library can parse URLs and split them to components. 39 | 40 | Synopsis 41 | ======== 42 | 43 | ```lua 44 | http { 45 | server { 46 | location /test { 47 | content_by_lua_block { 48 | local resty_url = require 'resty.url' 49 | 50 | ngx.say("USER: ", resty_url.parse('http://foo:bar@example.com').user) 51 | } 52 | } 53 | } 54 | } 55 | ``` 56 | 57 | [Back to TOC](#table-of-contents) 58 | 59 | Methods 60 | ======= 61 | 62 | All the methods are expected to be called on the module without self. 63 | 64 | [Back to TOC](#table-of-contents) 65 | 66 | split 67 | --- 68 | `syntax: parts = resty_url.split(url)` 69 | 70 | Returns a table with integer keys and parts of the URL. 71 | Components are: scheme, user, password, host, port, path. 72 | 73 | [Back to TOC](#table-of-contents) 74 | 75 | parse 76 | ------- 77 | `syntax: uri = resty_url.parse(url)` 78 | 79 | Returns a table with components as keys. 80 | Components are: scheme, user, password, host, port, path. 81 | 82 | [Back to TOC](#table-of-contents) 83 | 84 | join 85 | ---------- 86 | `syntax: url = resty_url.join(base, part, ...)` 87 | 88 | Concatenates URI components into resulting URL. Also normalizes URI to remove double slashes. 89 | Can concatenate objects returned by `parse` method. 90 | 91 | [Back to TOC](#table-of-contents) 92 | 93 | default\_port 94 | ------------ 95 | `syntax: port = resty_url.default_port(scheme)` 96 | 97 | Returns default port for given scheme. Only http and https provided by default. 98 | 99 | [Back to TOC](#table-of-contents) 100 | 101 | normalize 102 | ------------ 103 | `syntax: uri = resty_url.normalize(uri)` 104 | 105 | Removes unnecessary slashes from the URI. 106 | 107 | [Back to TOC](#table-of-contents) 108 | 109 | Installation 110 | ============ 111 | 112 | If you are using the OpenResty bundle (http://openresty.org ), then 113 | you can use [opm](https://github.com/openresty/opm#synopsis) to install this package. 114 | 115 | ```shell 116 | opm get 3scale/lua-resty-url 117 | ``` 118 | 119 | [Back to TOC](#table-of-contents) 120 | 121 | Bugs and Patches 122 | ================ 123 | 124 | Please report bugs or submit patches by 125 | 126 | 1. creating a ticket on the [GitHub Issue Tracker](http://github.com/3scale/lua-resty-url/issues), 127 | 128 | [Back to TOC](#table-of-contents) 129 | 130 | Author 131 | ====== 132 | 133 | Michal "mikz" Cichra , Red Hat Inc. 134 | 135 | [Back to TOC](#table-of-contents) 136 | 137 | Copyright and License 138 | ===================== 139 | 140 | This module is licensed under the Apache License Version 2.0. 141 | 142 | Copyright (C) 2016-2017, Red Hat Inc. 143 | 144 | All rights reserved. 145 | 146 | See [LICENSE](LICENSE) for the full license. 147 | 148 | [Back to TOC](#table-of-contents) 149 | 150 | See Also 151 | ======== 152 | * the APIcast API Gateway: https://github.com/3scale/apicast/#readme 153 | 154 | [Back to TOC](#table-of-contents) 155 | -------------------------------------------------------------------------------- /Roverfile: -------------------------------------------------------------------------------- 1 | luarocks { 2 | group 'test' { 3 | module { 'busted' }, 4 | module { 'benchmark-ips' }, 5 | }, 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /Roverfile.lock: -------------------------------------------------------------------------------- 1 | benchmark-ips 0.0.1-0|1ea3f04a758f696652549cdc720ac4b676bf609c|test 2 | busted 2.0.rc12-1||test 3 | dkjson 2.5-2||test 4 | lua-term 0.7-1||test 5 | lua_cliargs 3.0-1||test 6 | luafilesystem 1.7.0-2||test 7 | luassert 1.7.10-0||test 8 | luasystem 0.2.1-0||test 9 | mediator_lua 1.1.2-0||test 10 | penlight 1.5.4-1||test 11 | say 1.3-1||test -------------------------------------------------------------------------------- /benchmark/split.lua: -------------------------------------------------------------------------------- 1 | require('resty.core') 2 | 3 | local url = require('resty.url') 4 | local http = require('resty.http') 5 | 6 | local split = url.split 7 | local parse_uri = http.parse_uri 8 | 9 | -- require("jit.v").start("dump.txt") 10 | -- require('jit.p').start('vl') 11 | -- require('jit.dump').start('bsx', 'jit.log') 12 | 13 | require('benchmark.ips')(function(b) 14 | b.time = 10 15 | b.warmup = 5 16 | 17 | b:report('parse_uri', function() return parse_uri(nil, 'http://example.com:8080/path?query') end) 18 | b:report('split', function() return split('http://example.com:8080/path?query') end) 19 | 20 | 21 | b:compare() 22 | end) 23 | -------------------------------------------------------------------------------- /bin/busted: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env resty 2 | 3 | if ngx ~= nil then 4 | ngx.exit = function()end 5 | end 6 | 7 | -- Busted command-line runner 8 | require 'busted.runner'({ standalone = false }) 9 | 10 | -------------------------------------------------------------------------------- /dist.ini: -------------------------------------------------------------------------------- 1 | # distribution config for opm packaging 2 | name = lua-resty-url 3 | abstract = URL parser 4 | author = Michal Cichra (mikz) 5 | is_original = yes 6 | license = apache2 7 | lib_dir = src 8 | doc_dir = . 9 | repo_link = https://github.com/3scale/lua-resty-url 10 | main_module = src/resty/url.lua 11 | requires = ngx_http_lua 12 | -------------------------------------------------------------------------------- /rockspecs/lua-resty-url-0.3.3-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "lua-resty-url" 2 | version = "0.3.3-1" 3 | source = { 4 | url = "https://github.com/3scale/lua-resty-url/archive/v0.3.3.tar.gz", 5 | md5 = "f9e5a499fd9d6a401b51ff6fe448cbfe", 6 | dir = "lua-resty-url-0.3.3", 7 | } 8 | description = { 9 | summary = "lua-resty-url - URL parser", 10 | detailed = "lua-resty-url - URL parser using `ngx.re`", 11 | homepage = "https://github.com/3scale/lua-resty-url", 12 | license = "Apache License 2.0", 13 | } 14 | dependencies = { 15 | } 16 | build = { 17 | type = "builtin", 18 | modules = { 19 | ["resty.url"] = "src/resty/url.lua" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rockspecs/lua-resty-url-0.3.5-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "lua-resty-url" 2 | version = "0.3.5-1" 3 | source = { 4 | url = "https://github.com/3scale/lua-resty-url/archive/v0.3.5.tar.gz", 5 | md5 = "98d0eff455728a51513608ef208d46cc", 6 | dir = "lua-resty-url-0.3.5", 7 | } 8 | description = { 9 | summary = "lua-resty-url - URL parser", 10 | detailed = "lua-resty-url - URL parser using `ngx.re`", 11 | homepage = "https://github.com/3scale/lua-resty-url", 12 | license = "Apache License 2.0", 13 | } 14 | dependencies = { 15 | } 16 | build = { 17 | type = "builtin", 18 | modules = { 19 | ["resty.url"] = "src/resty/url.lua" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rockspecs/lua-resty-url-scm-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "lua-resty-url" 2 | version = "scm-1" 3 | source = { 4 | url = "git+https://github.com/3scale/lua-resty-url.git" 5 | } 6 | description = { 7 | summary = "lua-resty-url - URL parser", 8 | detailed = "lua-resty-url - URL parser using `ngx.re`", 9 | homepage = "https://github.com/3scale/lua-resty-url", 10 | license = "Apache License 2.0" 11 | } 12 | dependencies = { 13 | } 14 | build = { 15 | type = "builtin", 16 | modules = { 17 | ["resty.url"] = "src/resty/url.lua" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spec/resty/url_spec.lua: -------------------------------------------------------------------------------- 1 | local url = require 'resty.url' 2 | local tostring = tostring 3 | 4 | describe('resty.url', function() 5 | 6 | describe('.default_port', function() 7 | local default_port = url.default_port 8 | 9 | it('returns 80 for http', function() 10 | assert.equal(80, default_port('http')) 11 | end) 12 | 13 | it('returns 443 for https', function() 14 | assert.equal(443, default_port('https')) 15 | end) 16 | 17 | it('returns nil for everything else', function() 18 | assert.falsy(default_port('ftp')) 19 | end) 20 | end) 21 | 22 | describe('.split', function() 23 | local split = url.split 24 | 25 | it('works with port', function() 26 | assert.same({'https', false, false, 'example.com', '8443'}, 27 | split('https://example.com:8443')) 28 | end) 29 | 30 | it('works with user', function() 31 | assert.same({'https', 'user', false, 'example.com', false }, 32 | split('https://user@example.com')) 33 | end) 34 | 35 | it('works with user and password', function() 36 | assert.same({'https', 'user', 'password', 'example.com', false }, 37 | split('https://user:password@example.com')) 38 | end) 39 | 40 | it('works with just password', function() 41 | assert.same({'redis', false, 'password', 'example.com', false }, 42 | split('redis://:password@example.com')) 43 | end) 44 | 45 | it('works with dots and dashes in host', function() 46 | assert.same({'https', false, false, 'some-test.example.com', false, '/path' }, 47 | split('https://some-test.example.com/path')) 48 | end) 49 | 50 | it('works with underscores in host', function() 51 | assert.same({'http', false, false, 'http_client_backend', '1984' }, 52 | split('http://http_client_backend:1984')) 53 | end) 54 | 55 | it('works with numbers in host', function() 56 | assert.same({'https', false, false, '3scale.net', false }, 57 | split('https://3scale.net')) 58 | end) 59 | 60 | it('works uppercase in host', function() 61 | assert.same({'https', false, false, '3SCALE.net', false }, 62 | split('https://3SCALE.net')) 63 | end) 64 | 65 | it('works with port and path', function() 66 | assert.same({'http', false, false, 'example.com', '8080', '/path'}, 67 | split('http://example.com:8080/path')) 68 | end) 69 | 70 | it('removes the trailing slash', function() 71 | assert.same({'http', false, false, 'api.twitter.com', false }, 72 | split('http://api.twitter.com/')) 73 | end) 74 | 75 | it('works with redis DSN', function() 76 | assert.same({'redis', 'user', 'pass', 'localhost', '6379', '/42' }, 77 | split('redis://user:pass@localhost:6379/42', 'redis')) 78 | end) 79 | 80 | it('works with IPv4 host', function() 81 | assert.same({'https', false, false, '195.47.235.3', '443', '/path'}, 82 | split('https://195.47.235.3:443/path')) 83 | end) 84 | 85 | it('works with IPv6 host', function() 86 | assert.same({'https', false, false, '[2a02:38::1001]', '443', '/path'}, 87 | split('https://[2a02:38::1001]:443/path')) 88 | end) 89 | end) 90 | 91 | describe('.parse', function() 92 | local parse = url.parse 93 | 94 | it('works with port', function() 95 | assert.same({ scheme = 'https', host ='example.com', port = 8443 }, 96 | parse('https://example.com:8443')) 97 | end) 98 | 99 | it('works with user', function() 100 | assert.same({ scheme = 'https', user = 'user', host = 'example.com' }, 101 | parse('https://user@example.com')) 102 | end) 103 | 104 | it('works with user and password', function() 105 | assert.same({ scheme = 'https', user = 'user', password = 'password', host = 'example.com' }, 106 | parse('https://user:password@example.com')) 107 | end) 108 | 109 | it('works with port and path', function() 110 | assert.same({ scheme = 'http', host = 'example.com', port = 8080, path = '/path'}, 111 | parse('http://example.com:8080/path')) 112 | end) 113 | 114 | it('removes the trailing slash', function() 115 | assert.same({ scheme = 'http', host = 'api.twitter.com' }, 116 | parse('http://api.twitter.com/')) 117 | end) 118 | 119 | it('works with redis DSN', function() 120 | assert.same({ scheme = 'redis', user = 'user', password = 'pass', host = 'localhost', port = 6379, path = '/42' }, 121 | parse('redis://user:pass@localhost:6379/42', 'redis')) 122 | end) 123 | 124 | it('works with IPv4 host', function() 125 | assert.same({ scheme = 'https', host = '195.47.235.3', port = 443, path = '/path'}, 126 | parse('https://195.47.235.3:443/path')) 127 | end) 128 | 129 | it('works with IPv6 host', function() 130 | assert.same({ scheme = 'https', host = '[2a02:38::1001]', port = 443, path = '/path'}, 131 | parse('https://[2a02:38::1001]:443/path')) 132 | end) 133 | 134 | it('serializes back', function() 135 | local uri = 'https://user:password@example.com:1234/path?query' 136 | assert.equal(uri, tostring(parse(uri))) 137 | end) 138 | 139 | it('works with data-uri', function() 140 | local opaque = [[application/json;charset=utf-8;base64,eyJzZXJ2aWNlcyI6W3siaWQiOjEyMzQsImJhY2tlbmRfdmVyc2lvbiI6MSwicHJveHkiOnsiYXBpX2JhY2tlbmQiOiJodHRwOi8vMTI3LjAuMC4xOjgwODEiLCJob3N0bmFtZV9yZXdyaXRlIjoiZWNobyIsImhvc3RzIjpbImxvY2FsaG9zdCIsIjEyNy4wLjAuMSJdLCJiYWNrZW5kIjp7ImVuZHBvaW50IjoiaHR0cDovLzEyNy4wLjAuMTo4MDgxIiwiaG9zdCI6ImVjaG8ifSwicG9saWN5X2NoYWluIjpbeyJuYW1lIjoiYXBpY2FzdC5wb2xpY3kuYXBpY2FzdCJ9XSwicHJveHlfcnVsZXMiOlt7Imh0dHBfbWV0aG9kIjoiR0VUIiwicGF0dGVybiI6Ii8iLCJtZXRyaWNfc3lzdGVtX25hbWUiOiJoaXRzIiwiZGVsdGEiOjF9LHsiaHR0cF9tZXRob2QiOiJQT1NUIiwicGF0dGVybiI6Ii8iLCJtZXRyaWNfc3lzdGVtX25hbWUiOiJoaXRzIiwiZGVsdGEiOjF9LHsiaHR0cF9tZXRob2QiOiJQVVQiLCJwYXR0ZXJuIjoiLyIsIm1ldHJpY19zeXN0ZW1fbmFtZSI6ImhpdHMiLCJkZWx0YSI6MX1dfX1dfQ==]] 141 | local uri = 'data:' .. opaque 142 | assert.same({ scheme = 'data', opaque = opaque }, parse(uri)) 143 | end) 144 | end) 145 | 146 | describe('.join', function() 147 | local join = url.join 148 | 149 | it('works with a slash', function() 150 | assert.same('https://example.com/foo', join('https://example.com', '/foo')) 151 | end) 152 | 153 | it('works without a slash', function() 154 | assert.same('https://example.com/foo', join('https://example.com', 'foo')) 155 | end) 156 | 157 | it('works on parsed url', function() 158 | local uri = url.parse('http://example.com/foo') 159 | 160 | assert.same('http://example.com/foo/bar', join(uri, '/bar')) 161 | end) 162 | end) 163 | 164 | describe('.normalize', function() 165 | local normalize = url.normalize 166 | 167 | it('normalizes slases in path', function() 168 | assert.same('https://example.com/foo/bar/baz', normalize('https://example.com/foo///bar//baz')) 169 | end) 170 | 171 | it('not normalizes file scheme', function() 172 | assert.same('file:///var/test/folder', normalize('file:///var/test//folder')) 173 | end) 174 | end) 175 | end) 176 | -------------------------------------------------------------------------------- /src/resty/url.lua: -------------------------------------------------------------------------------- 1 | local tostring = tostring 2 | local re_match = ngx.re.match 3 | local concat = table.concat 4 | local tonumber = tonumber 5 | local setmetatable = setmetatable 6 | local re_gsub = ngx.re.gsub 7 | local select = select 8 | local find = string.find 9 | local sub = string.sub 10 | local assert = assert 11 | 12 | local _M = { 13 | _VERSION = '0.3.4', 14 | 15 | ports = { 16 | https = 443, 17 | http = 80, 18 | } 19 | } 20 | 21 | function _M.default_port(scheme) 22 | return _M.ports[scheme] 23 | end 24 | 25 | function _M.scheme(url) 26 | local start = find(url, ':', 1, true) 27 | 28 | if start then 29 | return sub(url, 1, start - 1), sub(url, start + 1) 30 | end 31 | end 32 | 33 | 34 | local core_base = require "resty.core.base" 35 | local core_regex = require "resty.core.regex" 36 | local new_tab = core_base.new_tab 37 | local C = require('ffi').C 38 | 39 | local function compile_regex(pattern) 40 | local compiled, err, flags = core_regex.re_match_compile(pattern, 'joxi') 41 | 42 | assert(compiled, err) 43 | 44 | return compiled, flags 45 | end 46 | 47 | local collect_captures = core_regex.collect_captures 48 | local abs_regex, abs_regex_flags = compile_regex([=[ 49 | ^ 50 | (?:(\w+):)? # scheme (1) 51 | // 52 | (?: 53 | ([^:@]+)? # user (2) 54 | (?: 55 | : 56 | ([^@]+)? # password (3) 57 | )? 58 | @)? 59 | ( # host (4) 60 | [a-z\.\-\d\_]+ # domain 61 | | 62 | [\d\.]+ # ipv4 63 | | 64 | \[[a-f0-9\:]+\] # ipv6 65 | ) 66 | (?: 67 | :(\d+) # port (5) 68 | )? 69 | (.*) # path (6) 70 | $ 71 | ]=]) 72 | local http_regex, http_regex_flags = compile_regex('^https?$') 73 | 74 | local function match(str, regex, flags) 75 | local res = new_tab(regex.ncaptures, regex.name_count) 76 | if not str then return false, res end 77 | 78 | local rc = C.ngx_http_lua_ffi_exec_regex(regex, flags, str, #str, 0) 79 | 80 | return rc > 0, collect_captures(regex, rc, str, flags, res) 81 | end 82 | 83 | local function _match_opaque(scheme, opaque) 84 | if match(scheme, http_regex, http_regex_flags) then 85 | return nil, 'invalid endpoint' 86 | end 87 | 88 | return { scheme, opaque = opaque } 89 | end 90 | 91 | local function _transform_match(m) 92 | m[0] = nil 93 | 94 | if m[6] == '' or m[6] == '/' then m[6] = nil end 95 | 96 | return m 97 | end 98 | 99 | function _M.split(url, protocol) 100 | if not url then 101 | return nil, 'missing endpoint' 102 | end 103 | 104 | local scheme, opaque = _M.scheme(url) 105 | 106 | if not scheme then return nil, 'missing scheme' end 107 | 108 | if protocol and not re_match(scheme, protocol, 'oj') then 109 | return nil, 'invalid protocol' 110 | end 111 | 112 | local ok, m = match(url, abs_regex, abs_regex_flags) 113 | 114 | if ok then 115 | return _transform_match(m) 116 | else 117 | return _match_opaque(scheme, opaque) 118 | end 119 | end 120 | 121 | function _M.parse(url, protocol) 122 | local parts, err = _M.split(url, protocol) 123 | 124 | if err then 125 | return parts, err 126 | end 127 | 128 | -- https://tools.ietf.org/html/rfc3986#section-3 129 | return setmetatable({ 130 | scheme = parts[1] or nil, 131 | user = parts[2] or nil, 132 | password = parts[3] or nil, 133 | host = parts[4] or nil, 134 | port = tonumber(parts[5]), 135 | path = parts[6] or nil, 136 | opaque = parts.opaque, 137 | }, { __tostring = function() return url end }) 138 | end 139 | 140 | function _M.normalize(uri) 141 | local regex = [=[ 142 | ( # Capture group 143 | 144 | (?