[
  {
    "path": ".gitignore",
    "content": "*.lock\n*.log.*\n*_temp\n\n### Lua template\n# Compiled Lua sources\nluac.out\n\n# luarocks build files\n*.src.rock\n*.zip\n*.tar.gz\n\n# Object files\n*.o\n*.os\n*.ko\n*.obj\n*.elf\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Libraries\n*.lib\n*.a\n*.la\n*.lo\n*.def\n*.exp\n\n# Shared objects (inc. Windows DLLs)\n*.dll\n*.so\n*.so.*\n*.dylib\n\n# Executables\n*.exe\n*.out\n*.app\n*.i*86\n*.x86_64\n*.hex\n\n### Node template\n# Logs\nlogs\n*.log\nnpm-debug.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directory\n# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git\nnode_modules\n### Go template\n# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n\n# Created by .ignore support plugin (hsz.mobi)\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2016 Apigee Corp\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "Accessing Go via Lua\n====================\n\nThis module enables easy access to Go modules from LuaJit and therefore, NGINX with the LuaJit module. So if you need the capabilities of Go in your NGINX processing, you've come to the right place!\n\nNote: Lua2Go is now available from LuaRocks: http://luarocks.org/modules/scottganyo/lua2go\n\nTo use (see also the [example](./example):\n\n1. Write your Go module and `export` your functions:\n\n    ```\n    //export add\n    func add(operand1 int, operand2 int) int {\n        return operand1 + operand2\n    }\n    ```\n\n2. Build your go module as a shared library:\n\n    `go build -buildmode=c-shared -o example.so example.go`\n\n3. Include a bit of setup in your Lua file:\n\n    ```\n    local lua2go = require('lua2go')\n    local example = lua2go.Load('./example.so')\n    ```\n\n4. Register your `extern` declarations from your header file (`example.h`) in your Lua:\n\n    ```\n    lua2go.Externs[[\n      extern GoInt add(GoInt p0, GoInt p1);\n    ]]\n    ```\n\n5. Call your Go function from Lua (see [example](./example) for more detail):\n\n    ```\n    local result = lua2go.ToGo(example.add(1, 1))\n    ```\n\n6. Run your app:\n\n    `luajit myapp.lua`\n\n7. Bask in the glory of all that you've accomplished!\n\n8. To see how Lua2Go can be incorporated into NGINX, check out the [benchmark](./benchmark) example.\n\nEnjoy!\n"
  },
  {
    "path": "benchmark/README.md",
    "content": "Benchmarking Go via LuaJit in nginx\n===================================\n\n1. build the benchmark library\n\n    ```\n    cd go\n    go build -buildmode=c-shared -o benchmark.so benchmark.go\n    cd ..\n    ```\n\n2. install openresty (or nginx w/ LuaJit library)\n\n3. add localhost aliases: 'local', 'proxy', and 'target' to your /etc/hosts\n\n4. execute: `openresty -p $PWD -c conf/nginx.conf`\n\n5. start node proxy (optional)\n\n    ```\n    cd node\n    npm install\n    node app.js\n    ```\n\n6. You will now have the following endpoints to hit for various benchmarks:\n\n    `http://localhost:3000/echo` : nginx echo\n\n    `http://localhost:3000/file` : nginx serve small static file\n\n    `http://localhost:3000/lua2go` : nginx -> lua2go -> benchmark.go, echo result\n\n    In addition, the following endpoints will proxy nginx -> nginx:\n\n    `http://localhost:3001/echo` : nginx proxy_pass -> target nginx echo\n\n    `http://localhost:3001/file` : nginx proxy_pass -> target nginx serve small static file\n\n    `http://localhost:3001/lua2go` : nginx -> lua2go -> benchmark.go -> rewrite -> /echo\n\n    And, if you ran the node proxy, the following endpoints will proxy node -> nginx:\n\n    `http://localhost:3003/echo` : node -> nginx echo\n\n    `http://localhost:3003/file` : nginx serve small static file\n\n7. Run your own benchmarks! I don't have a script. :)\n\n    You can install weighttp and try something like this:\n\n    `weighttp -n 1000 -c 128 -t 128 -k -H \"User-Agent: Me\" localhost:3000/lua2go`\n"
  },
  {
    "path": "benchmark/conf/nginx.conf",
    "content": "worker_processes  4;\n\nerror_log /dev/stderr;\nerror_log error.log;\n\nevents {\n  worker_connections 1024;\n}\n\nhttp {\n\n#  lua_code_cache off;\n  lua_package_path \"../lua/?.lua;;;\";\n\n  upstream target {\n    server localhost:3002;\n  }\n\n  init_by_lua_block {\n    ffi = require('ffi')\n    lua2go = require('lua2go')\n\n    -- copied from benchmark.h\n    ffi.cdef[[\n      extern GoString process(GoString method, GoString headers, GoString body);\n    ]]\n   }\n\n  root ./;\n\n  # responds from the local (initial) nginx\n  server {\n    server_name localhost;\n    listen 3000;\n\n    # for static page call /file\n    location / {\n    }\n\n    location /echo {\n      echo local_;\n    }\n\n    location /lua2go {\n      content_by_lua_block {\n        local benchmark = require('lua/benchmark')\n        local result = benchmark.run()\n        ngx.say(result)\n      }\n    }\n  }\n\n  # responds by proxying to the \"target\" nginx\n  server {\n    server_name localhost;\n    listen 3001;\n\n    location / {\n      proxy_pass http://target;\n    }\n\n    location /echo {\n      proxy_pass http://target/echo;\n    }\n\n    location /lua2go {\n      rewrite_by_lua_block {\n        local benchmark = require('lua/benchmark')\n        local result = benchmark.run()\n        -- result = ngx.location.capture('/echo')\n        -- ngx.say(result.body)\n        ngx.req.set_uri('/echo', true)\n      }\n    }\n  }\n\n  # the \"target\" nginx is an echo server\n  server {\n    server_name localhost;\n    listen 3002;\n\n    # for static page call /file\n    location / {\n    }\n\n    location /echo {\n      echo target;\n    }\n  }\n}\n"
  },
  {
    "path": "benchmark/file",
    "content": "afile\n"
  },
  {
    "path": "benchmark/go/benchmark.go",
    "content": "package main\n\nimport \"C\"\nimport \"strconv\"\n\nvar counter = 0\n\n//export process\nfunc process(method string, headers string, body string) string {\n  counter = counter + 1\n\treturn \"lua2go\" + strconv.Itoa(counter)\n}\n\nfunc main() {}\n"
  },
  {
    "path": "benchmark/go/benchmark.h",
    "content": "/* Created by \"go tool cgo\" - DO NOT EDIT. */\n\n/* package command-line-arguments */\n\n/* Start of preamble from import \"C\" comments.  */\n\n\n\n\n/* End of preamble from import \"C\" comments.  */\n\n\n/* Start of boilerplate cgo prologue.  */\n\n#ifndef GO_CGO_PROLOGUE_H\n#define GO_CGO_PROLOGUE_H\n\ntypedef signed char GoInt8;\ntypedef unsigned char GoUint8;\ntypedef short GoInt16;\ntypedef unsigned short GoUint16;\ntypedef int GoInt32;\ntypedef unsigned int GoUint32;\ntypedef long long GoInt64;\ntypedef unsigned long long GoUint64;\ntypedef GoInt64 GoInt;\ntypedef GoUint64 GoUint;\ntypedef __SIZE_TYPE__ GoUintptr;\ntypedef float GoFloat32;\ntypedef double GoFloat64;\ntypedef __complex float GoComplex64;\ntypedef __complex double GoComplex128;\n\n// static assertion to make sure the file is being used on architecture\n// at least with matching size of GoInt.\ntypedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];\n\ntypedef struct { char *p; GoInt n; } GoString;\ntypedef void *GoMap;\ntypedef void *GoChan;\ntypedef struct { void *t; void *v; } GoInterface;\ntypedef struct { void *data; GoInt len; GoInt cap; } GoSlice;\n\n#endif\n\n/* End of boilerplate cgo prologue.  */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\nextern GoString process(GoString p0, GoString p1, GoString p2);\n\n#ifdef __cplusplus\n}\n#endif\n"
  },
  {
    "path": "benchmark/lua/benchmark.lua",
    "content": "-- called from nginx.conf\n\nlocal benchmark = {}\n\nfunction benchmark.run()\n\n  -- note: apigee externs are defined in nginx.confg\n  local benchmark = lua2go.Load('./go/benchmark.so')\n\n  local method = ngx.req.get_method()\n\n  local no_request_line = true\n  local rawHeaders = ngx.req.raw_header(no_request_line)\n\n  local body = ngx.req.get_body_data() or '' -- cannot be nil\n\n  local goResult = benchmark.process(lua2go.ToGo(method), lua2go.ToGo(rawHeaders), lua2go.ToGo(body))\n\n  return lua2go.ToLua(goResult)\nend\n\nreturn benchmark\n"
  },
  {
    "path": "benchmark/node/app.js",
    "content": "'use strict'\n\nconst connect = require('connect')\nconst http = require('http')\nconst debug = require('debug')('test')\nconst microgateway = require('microgateway-core')\nconst config = require('config')\n\nconst gateway = microgateway(config)\n\ndebug('starting gateway')\n\ngateway.start((err, server) => {\n  if (err) {\n    debug('gateway err %o', err)\n    process.exit(1)\n  }\n\n  debug('gateway started')\n})\n"
  },
  {
    "path": "benchmark/node/config/default.yaml",
    "content": "edgemicro:\n  port: 3003\n  logging:\n    level: warn\nproxies:\n- base_path: /\n  url: http://localhost:3002\n"
  },
  {
    "path": "benchmark/node/package.json",
    "content": "{\n  \"name\": \"microproxy\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"app.js\",\n  \"author\": \"Scott Ganyo\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"config\": \"^1.19.0\",\n    \"connect\": \"^3.3.5\",\n    \"debug\": \"^2.2.0\",\n    \"js-yaml\": \"^3.5.5\",\n    \"microgateway-core\": \"git@github.com:apigee/microgateway-core.git\"\n  },\n  \"scripts\": {\n    \"start\": \"node app.js\"\n  }\n}\n"
  },
  {
    "path": "example/example.go",
    "content": "package main\n\nimport (\n\t\"C\"\n  \t\"strings\"\n)\n\n\n//export add\nfunc add(operand1 int, operand2 int) int {\n\treturn operand1 + operand2\n}\n\n//export concat\nfunc concat(elements []string, separator string) *C.char {\n\t// This CString must be released by caller!\n\treturn C.CString(strings.Join(elements, separator))\n}\n\n//export increment\nfunc increment(value *int) {\n\t*value = *value + 1\n}\n\n//export reverse\nfunc reverse(value []int) {\n\tfor i, j := 0, len(value) - 1; i < j; i, j = i + 1, j - 1 {\n\t\tvalue[i], value[j] = value[j], value[i]\n\t}\n}\n\nfunc main() {}\n"
  },
  {
    "path": "example/example.h",
    "content": "/* Created by \"go tool cgo\" - DO NOT EDIT. */\n\n/* package command-line-arguments */\n\n/* Start of preamble from import \"C\" comments.  */\n\n\n\n\n/* End of preamble from import \"C\" comments.  */\n\n\n/* Start of boilerplate cgo prologue.  */\n\n#ifndef GO_CGO_PROLOGUE_H\n#define GO_CGO_PROLOGUE_H\n\ntypedef signed char GoInt8;\ntypedef unsigned char GoUint8;\ntypedef short GoInt16;\ntypedef unsigned short GoUint16;\ntypedef int GoInt32;\ntypedef unsigned int GoUint32;\ntypedef long long GoInt64;\ntypedef unsigned long long GoUint64;\ntypedef GoInt64 GoInt;\ntypedef GoUint64 GoUint;\ntypedef __SIZE_TYPE__ GoUintptr;\ntypedef float GoFloat32;\ntypedef double GoFloat64;\ntypedef float _Complex GoComplex64;\ntypedef double _Complex GoComplex128;\n\n/*\n  static assertion to make sure the file is being used on architecture\n  at least with matching size of GoInt.\n*/\ntypedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];\n\ntypedef struct { const char *p; GoInt n; } GoString;\ntypedef void *GoMap;\ntypedef void *GoChan;\ntypedef struct { void *t; void *v; } GoInterface;\ntypedef struct { void *data; GoInt len; GoInt cap; } GoSlice;\n\n#endif\n\n/* End of boilerplate cgo prologue.  */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\nextern GoInt add(GoInt p0, GoInt p1);\n\nextern char* concat(GoSlice p0, GoString p1);\n\nextern void increment(GoInt* p0);\n\nextern void reverse(GoSlice p0);\n\n#ifdef __cplusplus\n}\n#endif\n"
  },
  {
    "path": "example/example.lua",
    "content": "-- ensure the lua2go lib is on the LUA_PATH so it will load\n-- normally, you'd just put it on the LUA_PATH\npackage.path = package.path .. ';../lua/?.lua'\n\n-- load lua2go\nlocal lua2go = require('lua2go')\n\n-- load my Go library\nlocal example = lua2go.Load('./example.so')\n\n-- copy just the extern functions from benchmark.h into ffi.cdef structure below\n-- (the boilerplate cgo prologue is already defined for you in lua2go)\n-- this registers your Go functions to the ffi library..\nlua2go.Externs[[\n  extern GoInt add(GoInt p0, GoInt p1);\n  extern char* concat(GoSlice p0, GoString p1);\n  extern void increment(GoInt* p0);\n  extern void reverse(GoSlice p0);\n]]\n\n---------------------------------------------------------\n-- all set up, now you may call your Go functions!\n\n---------------------------------------------------------\n-- Let's do the easiest one first. We'll add two ints and return the result.\n\n-- note that Lua numbers in the parameters are auto-converted to GoInts (yay!)\n-- but... the result will still be a GoInt...\nlocal goAddResult = example.add(1, 1)\n\n-- which means we need to convert it - easy with a call to lua2go.ToLua()\n-- we use capitalized exported functions, so you Go folks feel right at home!\nlocal addResult = lua2go.ToLua(goAddResult)\n\nprint('1 + 1 = ' .. addResult)\n\n\n---------------------------------------------------------\n-- What about passing an int by reference? Also, super easy!\n\nlocal value = 2\n\n-- create a Go pointer to the value\nlocal intPtr = lua2go.ToGoPointer(value)\n\n-- call increment, passing the pointer\nexample.increment(intPtr)\n\n-- use [0] to deference the pointer\nlocal newValue = lua2go.ToLua(intPtr[0])\n\nprint(value .. ' + 1 = ' .. newValue)\n\n\n--------------------------------------------------------------------\n-- Numbers are easy, but what about passing a Go Slice by reference?\n-- We'll reverse a Slice of numbers\n\n-- Note: Go Slice support is rudimentory right now and subject to change\n\n-- we'll reverse these values\nlocal values = { 1, 2, 3 }\n\n-- hold on to both results\n-- we'll give Go the slice, but we need the array for iteration\nlocal goSlice, goArray = lua2go.ToGoSlice(values)\n\n-- pass the slice to Go to reverse\nexample.reverse(goSlice)\n\n-- print the reversed array\n-- note: this is a Go Array, so it's zero-indexed\nlocal countDown = ''\nfor i = 0, #values - 1 do\n  countDown = countDown .. ' ...' .. lua2go.ToLua(goArray[i])\nend\nprint(\"The final countdown\" .. countDown)\n\n\n--------------------------------------------------------------------------\n-- Finally, let's concat an table together and return a new string from Go\n\n-- we'll start with a table of strings\nlocal strings = {\n  'Lua2Go',\n  'is',\n  'pretty',\n  'cool!'\n}\n\n-- then convert the table to a slice of Go strings\nlocal goSliceOfStrings = lua2go.ToGoSlice(strings)\n\n-- make a GoString for the separator\nlocal separator = lua2go.ToGo(' ')\n\n-- call our Go concat function\nlocal result = example.concat(goSliceOfStrings, separator)\n\n-- Important: Go allocated the return value, so we'll need to deallocate it!\n-- tell the Lua garbage collector to handle this for us\nlua2go.AddToGC(result)\n\n-- convert to Lua\nlocal luaConcatResult = lua2go.ToLua(result)\n\nprint(luaConcatResult)\n"
  },
  {
    "path": "lua/lua2go.lua",
    "content": "--[[\n\n A library for calling into Go from LuaJit\n\n--]]\n\nlocal lua2go = {}\n\nlocal ffi = require('ffi')\n\nffi.cdef[[\n  // standard Go definitions //\n\n  typedef signed char GoInt8;\n  typedef unsigned char GoUint8;\n  typedef short GoInt16;\n  typedef unsigned short GoUint16;\n  typedef int GoInt32;\n  typedef unsigned int GoUint32;\n  typedef long long GoInt64;\n  typedef unsigned long long GoUint64;\n  typedef GoInt64 GoInt;\n  typedef GoUint64 GoUint;\n  typedef float GoFloat32;\n  typedef double GoFloat64;\n  typedef __complex float GoComplex64;\n  typedef __complex double GoComplex128;\n\n  // static assertion to make sure the file is being used on architecture\n  // at least with matching size of GoInt.\n  typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];\n\n  // change to Go struct: add 'const' declaration to char * (required by Lua FFI)\n  // typedef struct { char *p; GoInt n; } GoString;\n  typedef struct { const char *p; GoInt n; } GoString;\n\n  typedef void *GoMap;\n  typedef void *GoChan;\n  typedef struct { void *t; void *v; } GoInterface;\n  typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;\n\n  // C stdlib definitions //\n\n  void free(void *ptr);\n]]\n\nlocal makeGoString = ffi.typeof('GoString')\nlocal makeGoSlice = ffi.typeof('GoSlice')\nlocal makeGoStringArray = ffi.typeof('GoString[?]')\nlocal makeGoIntArray = ffi.typeof('GoInt[?]')\nlocal identity = function(x) return x end\n\n-- types: \"nil\", \"number\", \"string\", \"boolean\", \"table\", \"function\", \"thread\", or \"userdata\"\nlocal goTypes = {\n  number = 'GoInt',\n  string = 'GoString'\n}\n\nlocal goArrayConstructors = {\n  number = makeGoIntArray,\n  string = makeGoStringArray\n}\n\nlocal goConverters = {\n  number = identity\n}\ngoConverters['nil'] = identity\n\n\n--\n-- public interface\n--\n\n-- create cdata object\nlua2go.New = ffi.new\n\n-- add cdata to garbage collector, returns GC ref\nlua2go.AddToGC = function(cdata)\n  return ffi.gc(cdata, ffi.C.free)\nend\n\n-- returns the typeof the Go object\nlua2go.GoType = ffi.typeof\n\n-- loads and returns a Go library\nlua2go.Load = ffi.load\n\n-- defines loaded functions\nlua2go.Externs = ffi.cdef\n\n-- convert C String to Lua\nlua2go.ToLuaString = function(str)\n  if ffi.typeof(str) == makeGoString then\n    return ffi.string(str.p)\n  else\n    return ffi.string(str) -- assume char *\n  end\nend\n\n-- convert Number to Lua\nlua2go.ToLuaNumber = tonumber\n\n-- converts Lua String to a Go String\nfunction lua2go.ToGoString(str)\n  if str == nil then return '' end\n  return makeGoString({ str, #str })\nend\ngoConverters['string'] = lua2go.ToGoString\n\n-- returns the Go type a luaVar will map to\n-- currently supports Go strings and ints\nfunction lua2go.Type(luaVar)\n  local luaType = type(luaVar)\n  return goTypes[luaType]\nend\n\n-- retrieve a function to get the slice type for a lua table\n-- note: must be an array-style table, not a map\nfunction lua2go.SliceType(table)\n  return lua2go.Type(table[1])..'[?]'\nend\n\n-- will make a Go array that is either Ints or Strings based on the first element type\n-- must be an array-style table, not a map\n-- currently only supports string and ints\nfunction lua2go.ToGoArray(table)\n  local luaType = type(table[1])\n  local makeGoArray = goArrayConstructors[luaType]\n  local goArray = makeGoArray(#table)\n  local toGoType = goConverters[luaType]\n  for index, value in next, table do\n    goArray[index - 1] = toGoType(value)\n  end\n  return goArray\nend\ngoConverters['table'] = lua2go.ToGoArray\n\n\n-- will make a Go slice that is either Ints or Strings based on the first element type\n-- must be an array-style table, not a map\n-- returns GoSlice, backing array\nfunction lua2go.ToGoSlice(table)\n  local goArray = lua2go.ToGoArray(table)\n  return makeGoSlice({ goArray, #table, #table }), goArray\nend\n\n-- retrieve a function to convert the luaVar to a goVar based on the type of luaVar\n-- currently supports Go strings and ints\nfunction lua2go.Converter(luaVar)\n  return goConverters[type(luaVar)]\nend\n\n-- converts a goVar to a luaVar\n-- currently supports Go strings and ints\nfunction lua2go.ToLua(goVar)\n  if goVar == nil then return nil end\n  if ffi.istype('GoString', goVar) or ffi.istype('char *', goVar) then\n    return lua2go.ToLuaString(goVar)\n  elseif ffi.istype('GoInt', goVar) then\n    return lua2go.ToLuaNumber(goVar)\n  else\n    error('unknown type')\n  end\nend\n\n-- converts luaVar to goVar using simple type mapping\n-- currently only converts strings, numbers are left alone as they are converted automatically\nfunction lua2go.ToGo(luaVar)\n  local convert = lua2go.Converter(luaVar)\n  return convert(luaVar)\nend\n\n-- returns a pointer and a value holder variable\nfunction lua2go.ToGoPointer(luaVar)\n  local luaType = type(luaVar)\n  local makeGoArray = goArrayConstructors[luaType]\n  local ptr = makeGoArray(1, luaVar)\n  return ptr, ptr[0]\nend\n\nlocal module_mt = {\n  __newindex = (function (table, key, val) error('Attempt to write to undeclared variable \"' .. key .. '\"') end)\n}\nsetmetatable(lua2go, module_mt)\nreturn lua2go\n"
  },
  {
    "path": "lua2go-scm-1.rockspec",
    "content": " package = \"Lua2Go\"\n version = \"scm-1\"\n source = {\n    url = \"git://github.com/theganyo/lua2go\"\n }\n description = {\n    summary = \"Easy access to your Go (Golang) modules from Lua and NGINX\",\n    detailed = [[\n      This module enables easy access to Go modules from LuaJit and therefore,\n      NGINX with the LuaJit module. So if you need the capabilities of Go in \n      your NGINX processing, you've come to the right place!\n    ]],\n    homepage = \"https://github.com/theganyo/lua2go\",\n    license = \"Apache-2.0\"\n }\n dependencies = {\n    \"lua ~> 5.1\"\n }\n build = {\n    type = \"builtin\",\n    modules = {\n      lua2go = \"lua/lua2go.lua\"\n    }\n }"
  }
]