GETTING STARTED WITH THE OTTO JAVASCRIPT INTERPRETER
原文: https://www.fknsrs.biz/blog/otto-getting-started.html.html
While you're reading this, keep in mind that I'm available for hire! If you've got a JavaScript project getting out of hand, or a Golang program that's more "stop" than "go," feel free to get in touch with me. I might be able to help you. You can find my resume here.
JavaScript is by far the most popular scripting language around right now. Born in a web browser, it’s been leaking out into the rest of the software ecosystem for about ten years. JavaScript is great for expressing short pieces of logic, and for prototyping. There are a range of high quality, open source JavaScript engines available for various purposes. The most popular is probably V8, powering projects like node.js and the Atom text editor. While V8 is an incredibly well-optimised piece of software, and there are several bindings of it to Go, the API isn’t very well-suited to close integration with the Go language. Luckily, we have a solid JavaScript engine written in pure Go. It’s called otto, and I’d like to teach you the very basics of using it.
There are a few important things you need to know if you’d like to use otto. The first is that it’s purely an interpreter - there’s no JIT compilation or fancy optimisations. While performance is important, the primary focus of otto is on rich integration with Go. The second is that (right now!) it strictly targets ES5, the fifth edition of the ECMAScript standard, ECMA-262. This is relevant because ECMA-262 actually doesn’t define an event or I/O model. This means thatsetTimeout
, setInterval
, XMLHttpRequest
, fetch
, and any other related things are provided by external packages (e.g. fknsrs.biz/p/ottoext). There are a handful of browser APIs in otto (like the console
object), but for the most part, if it’s not in ECMA-262, it’s not in otto.
So! Now that we have that out of the way, let’s get into some specifics. First, I’ll describe some important parts of the API. Then we’ll take that information and make a real program out of it!
API
I’m going to be leaving a lot of functions out of this description. For a full listing of what’s available, check out the godoc page.
I’ll also be skipping error checking in these examples, but that’s just to save space. The full program listing below will include error handling.
type Otto
var vm otto.Otto
This type represents an interpreter instance. This is what you’ll use to actually run your JavaScript code. You can think of it as a tiny little self- contained JavaScript universe.
You can interact with this little universe in a variety of ways. You can put things into it (Set
), grab things out of it (Get
), and of course, run code in it (Run
).
func New() Otto
vm := otto.New()
The New
function is used to create an Otto instance. There’s some setup that has to happen, so you have to use this constructor function.
func (Otto) Set(name string, v interface{}) error
vm.Set("cool", true)
vm.Set("greet", func(name string) {
return fmt.Printf("hello, %s!\n", name)
})
You can use Set
to set global variables in the interpreter. v
can be a lot of different things. For simple values (strings, numbers, booleans, nil), you can probably guess what happens.
If v
is a more complex, but still built-in type (slice, map), it’ll be turned into the equivalent JavaScript value. For a slice, that’ll be an array. For a map, it’ll be an object.
If v
is a struct, it’ll be passed through to the interpreter as an object with properties that refer to the fields and functions of that struct.
If v
is a function, otto will map it through to a JavaScript function in the interpreter. Stay tuned for a more detailed article about this in the near future!
Under the hood, this actually uses a function called ToValue
.
func (Otto) Run(src interface{}) (Value, error)
vm.Run(`var a = 1;`)
The most obvious way to run code in the interpreter is the Run
function. This can take a string, a precompiled Script
object, an io.Reader
, or a Program
. The simplest option is a string, so that’s what we’ll be working with.
Run
will always run code in global scope. There’s also an Eval
method that will run code in the current interpreter scope, but I won’t be covering that in this article.
func (Otto) Get(name string) (Value, error)
val, _ := vm.Get("greet")
This is one way to get output from the interpreter. Get
will reach in and grab things out of the global scope. One important thing about this is that you can’t use Get
to retrieve variables that are declared inside functions.
func (Value) Export() (interface{}, error)
a, _ := val.Export()
fmt.Printf("%#v\n", a) // prints `1`
Export
does the inverse of what happens when you Set
a value. Instead of taking a Go value and making it into a JavaScript value, it makes a JavaScript value into something you can use in Go code.
func (Value) Call(this Value, args …interface{}) (Value, error)
fn, _ := vm.Get("greet")
fn.Call(otto.NullValue(), "friends")
Call
only works with functions. If you have a handle to a JavaScript function, you can execute it with a given context (i.e. this
value) and optionally some arguments.
The arguments are converted in the same way as the Set
function.
Call
returns (Value, error)
. The Value
is the return value of the JavaScript function. If the JavaScript code throws an exception, or there’s an internal error in otto, the error
value will be non-nil.
There also exists a Call(src string, this interface{}, args ...interface{}) (Value, error)
function on the Otto
object itself. This is a sort of combination of Otto.Run
andValue.Call
. It evaluates the first argument, then if it results in a function, calls that function with the given this
value and arguments.
A whole program
Let’s plug all these things together and see what we come up with!
Note: some of this will be formatted a little strangely to save space here.
package main
import (
"fmt"
"github.com/robertkrimen/otto"
)
func greet(name string) {
fmt.Printf("hello, %s!\n", name)
}
func main() {
vm := otto.New()
if err := vm.Set("greetFromGo", greet); err != nil {
panic(err)
}
// `hello, friends!`
if _, err := vm.Run(`greetFromGo('friends')`); err != nil {
panic(err)
}
if _, err := vm.Run(`function greetFromJS(name) {
console.log('hello, ' + name + '!');
}`); err != nil {
panic(err)
}
// `hello, friends!`
if _, err := vm.Call(`greetFromJS`, nil, "friends"); err != nil {
panic(err)
}
if _, err := vm.Run("var x = 1 + 1"); err != nil {
panic(err)
}
val, err := vm.Get("x")
if err != nil {
panic(err)
}
v, err := val.Export()
if err != nil {
panic(err)
}
// (all numbers in JavaScript are floats!)
// `float64: 2`
fmt.Printf("%T: %v\n", v, v)
if _, err := vm.Run(`function add(a, b) {
return a + b;
}`); err != nil {
panic(err)
}
r, err := vm.Call("add", nil, 2, 3)
if err != nil {
panic(err)
}
// `5`
fmt.Printf("%s\n", r)
}
So there you have it, a whole program. It calls a Go function from JavaScript, calls a JavaScript function from Go, sets some stuff, gets some stuff, runs some code, and exports a JavaScript value to a Go value.
There’s plenty more to play around with in the otto JavaScript interpreter, and I’ll be covering some of these features in more detail, so stay tuned for more!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2016-06-30 php中print_r 和var_dump 打印变量的区别。