Skip to content

Instantly share code, notes, and snippets.

@rag594
Created January 26, 2024 17:22
Show Gist options
  • Save rag594/57160c526621eedc30553b513129a096 to your computer and use it in GitHub Desktop.
Save rag594/57160c526621eedc30553b513129a096 to your computer and use it in GitHub Desktop.
gopher-lua-poc
package main
import (
"fmt"
"reflect"
"strings"
"github.com/yuin/gluamapper"
lua "github.com/yuin/gopher-lua"
)
type DLRequest struct {
Number string `json:"dl_number"`
Dob string `json:"dob"`
}
type DLSignzyRequest struct {
DlNumber string `json:"dlNumber"`
DateOfBirth string `json:"dob"`
}
var requestTypeMap = map[string]func() interface{}{
"DL": func() interface{} { return new(DLRequest) },
}
var dlGatewayRequestTypeMap = map[string]func() interface{}{
"SIGNZY": func() interface{} { return new(DLSignzyRequest) },
}
var gatewayRequestTypeMap = map[string]map[string]func() interface{}{
"DL": dlGatewayRequestTypeMap,
}
func getModel(request interface{}) *lua.LTable {
v := reflect.ValueOf(*&request)
typeOfV := v.Type()
modelTable := &lua.LTable{}
for i := 0; i < v.NumField(); i++ {
jsonTag := strings.Split(typeOfV.Field(i).Tag.Get("json"), ",")[0]
modelTable.RawSet(lua.LString(jsonTag), lua.LString(v.Field(i).Interface().(string)))
}
return modelTable
}
func transform(L *lua.LState, modelTable *lua.LTable, identityType string, gateway string) interface{} {
if err := L.CallByParam(lua.P{
Fn: L.GetGlobal("transform"),
NRet: 1,
Protect: true,
}, modelTable); err != nil {
panic(err)
}
ret := L.ToTable(-1) // returned value
vendorRequest := gatewayRequestTypeMap[identityType][gateway]()
if err := gluamapper.Map(ret, vendorRequest); err != nil {
panic(err)
}
L.Pop(1) // remove received value
return vendorRequest
}
func main() {
L := lua.NewState()
defer L.Close()
if err := L.DoString(`
function transform(m)
f = {}
f["dl_number"] = m["dl_number"]
f["date_of_birth"] = m["dob"]
return f
end
`); err != nil {
panic(err)
}
dlRequest := &DLRequest{Number: "KA51201934808024", Dob: "05-08-1994"}
modelTable := getModel(*dlRequest)
vendorRequest := transform(L, modelTable, "DL", "SIGNZY")
fmt.Println(vendorRequest.(*DLSignzyRequest).DlNumber)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment