Skip to content

Instantly share code, notes, and snippets.

@JalfResi
Created June 25, 2015 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JalfResi/fcd68104a284c3bf640d to your computer and use it in GitHub Desktop.
Save JalfResi/fcd68104a284c3bf640d to your computer and use it in GitHub Desktop.
Otto JS Plugin - expose host object to JS
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment