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