Golang Otto JS-将宿主对象公开到JavaScript

I'm trying to expose an existing Go Object to the Otto JavaSCript runtime. The object is exposed and I can see it, but when I call methods that affect the state of the exposed object, I get panics and errors or even just silent ignoring of it by Otto!

Golang code:

package main

import (
    "bytes"
    "fmt"
    "log"
    "os"

    "github.com/robertkrimen/otto"
)

type BensObject struct {
    name string
}

func (b BensObject) SetName(name string) {
    fmt.Println("INT: ", name)
    b.name = name
    fmt.Println("INT: ", b.name)
}

func (b BensObject) GetName() string {
    fmt.Println("INT: ", b.name)
    return b.name
}

func (b BensObject) Age() int {
    return 36
}

func (b BensObject) AddToAge(n int) int {
    return 36 + n
}

func main() {
    runtime := loadPluginRuntime("plugins.js")

    // If we don't have a runtime all requests are accepted
    if runtime == nil {
        os.Exit(-1)
    }

    r := new(BensObject)
    v, err := runtime.ToValue(*r)
    if err != nil {
        log.Fatal(err)
    }

    // By convention we will require plugins have a set name
    result, err := runtime.Call("checkRequest", nil, v)
    if err != nil {
        log.Fatal(err)
    }
    // If the js function did not return a bool error out
    // because the plugin is invalid
    out, err := result.ToBoolean()
    if err != nil {
        log.Fatalf("\"checkRequest\" must return a boolean. Got %s", err)
    }

    fmt.Println(out)
}

func loadPluginRuntime(name string) *otto.Otto {
    f, err := os.Open(name)
    if err != nil {
        if os.IsNotExist(err) {
            return nil
        }
        log.Fatal(err)
    }
    defer f.Close()
    buff := bytes.NewBuffer(nil)

    if _, err := buff.ReadFrom(f); err != nil {
        log.Fatal(err)
    }
    runtime := otto.New()
    // Load the plugin file into the runtime before we
    // return it for use
    if _, err := runtime.Run(buff.String()); err != nil {
        log.Fatal(err)
    }
    return runtime
}

JavaScript code:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

function checkRequest(r) {
    console.log(r);
    r.SetName("Ben");
    console.log(r.GetName());

    console.log(getKeys(r));
    console.log(r.Name);
    console.log(r.Age());
    console.log(r.AddToAge(10));
    return true
}

Does anyone have any insight? Has anyone been able to expose an already existing large object structure with methods to Ottos runtime? I have a very large Go package I'd like to expose directly to the Otto runtime without have to do too much fiddly and fragile "mapping" to JS.

查看全部
dongling0519
dongling0519
2015/06/26 14:22
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复