Example of implementing JavaScript with Golang

C ++ is too much trouble (difficult), I want to get the V8 is really hard, but the Golang community has a few JavaScript engines, and try to integrate javascript in other languages, it is a good choice. The following is the example of github.com/dop251/goja.

Hello World
Photo of the repository, one:

Package Mainimport “FMT” JS “GitHub.com/dop251/goja”)func main () {vm: = js.new () // Create Engine instance r, _: = vm.runstring (` 1 + 1 `) // execution JavaScript code v, _: = r.Export (). (int64) // converts the result of the result to Golang corresponding type FMT.Println (R)}
   
This example shows the most basic capabilities, given a JavaScript code text, which can perform a result, and can obtain representation of the host language of the execution result.

The interaction between javaScript and golaang is divided into two aspects: Golang injects some contexts into the JavaScript engine, such as registering some full-time functions for JavaScript Use, create an object, etc .; Golang reads some contexts from the JavaScript engine, such as a calculation result of a computing process. See the first category first. Commonly used means is that the SET method provided through the runtime type is registered globally, for example

…RTS: = js.new () RTS.SET (“X”, 2) RTS.RunString (`x + x`) // 4 …

 Signature Signature Signature is FUNC (R * Runtime) Set (Name String, Value Interface {}), for basic types, no additional packages can be automatically converted, but when you need to pass a complex object, you need newObject Packing:   
RTS: = js.new () o: = RTS.NEWObject () O.SET (“X”, 2) RTS.SET (“O” O “, o) RTS.RunString (` O.X + OX`) // 4
Switching to the angle of golang, is a natural process, wanting to create one Objects, you need to create a corresponding expression in Golang and then use it in JavaScript. For more complex objects, nesting is fine.

The definition function is different, and the difference is that the functions in JavaScript in Golang and other types of values ​​are not quite the same. The signature of the function in the golang is: func (js) .FunctionCall, js.value, js.functionCall contains context information for calling functions, based on this, we can try to add a console.log for JavaScript:

 . ..func log (call js.functioncall) js.value {str: = call.argument (0) fmt.print (Str.String ()) Return str} ... RTS: = JS.New () console: = RTS.NEWObject () Console.set ("log", log) RTS.Set ("console" rts.runstring (`Console.log ('Hello World')` // Hello World  
Compared to injecting some information into the JavaScript engine, read information is relatively simple, and a method is shown in the front Hello World, performing a JavaScript Code, then get a result. But this method is not flexible enough, if you want to get a context, the value of the variable is not so convenient. To this end, GoJA provides a GET method, and the Runtime type GET method can read information about a variable from the Runtime, and the Get method of the Object type can read the value of a field from the object. The signature is as follows: FUNC (R * Runtime) Get (Name String) Value, FUNC (O * Object) Get (Name String) Value. However, the type of obtained value is the value type. If you want to convert into a corresponding type, you need to convert it through some ways, here you will not repeat it, you are interested to go see its documentation.

GOJA value provides basic parsing of the ability to execute JavaScript code, but our common host provides power, need Use it to add yourself during use. Below, the ability to load local JavaScript code is provided based on the skills of the above.
 With Require, a COMMJS format JavaScript code, an intuitive process: According to the file name, read the text, assemble it into an immediate execution function, execute, then return to the Module object, but in the middle can do some small optimization, such as The code that has been loaded is not reloaded., Execute, just returning. Probably the following:   
Package Coreimport (“IO / IOUTIL” “Path / FilePath” JS “Github.com/dop251/goja”)func ModuleTemplate (C String) String {return (function (module, exports) {“+ CreateModule (C * core) * js.object {r: = C.GETRTS () m: = R.NewObject E: = r.newobject () M.SET (“Exports”, E) Return M} Func CompileModule (P String) * js.program {code, _: = Ioutil.ReadFile (p) text: = moduleTemplate (String (code)) PRG, _: = JS.Compile (p, text, false) Return prg} Func LoadModule (C * Core, P String) js.value {p = filepath.clean (p) PKG: = C.PKG [p] if pkg! = nil {return pkg} PRG: = CompileModule (P) R: = C.GETRTS () f, _: = r.Runprogram (PRG) g, _: = js.assertFunction (f) m : = CreateModule (c) jsexPorts: = M.GET (“Exports”) G (JSExports, M, JSExports) Return M.GET (“Exports”)} To allow the engine to use this capability, you need to register the RUNTIME in Runtime if you want the engine. / RegisterLoader Register A Simple Commonjs Style Loader To Runtimefunc RegisterLoader (C * Core) {r: = C.Getrts () R.Set (“Require”, Func (Call Js.FunctionCall) js.value {p: = CALL.Argument (0) .String () Return LoadModule (C, P)})}

Integr Example is interested in github.com/81120/gode

Write

The boundaries of the JavaScript engine and JavaScript execution environment have been previously clear, and this example has a very specific understanding. Moreover, there is a more clear understanding of the structure of Node itself. In some scenarios, some of the language needs to be embedded in another language to achieve some of the more flexible functionality and decoupling, such as nginx in lua, game engine lua, mongodb shell in Javascipt, and even provides a first official nginx The castrated version of JavaScript implements the DSL configured. Then, in this scenario in which you need to embed DSL, an execution engine embedded in a mature language is much easier than yourself. Moreover, in various scenarios, the requirements of the language itself are also different, such as edge computing scenes, embedding, can be developed with javascript, but is it necessary to need a complete V8? rightEnvironmental and performance have special requirements, limit DSL, provide the necessary host language extension is also a good idea.

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment