Go Eval library
Golang
of eval()
function third-party implementations.
background
As we all know, Golang
is a static language. As an old comrade who switched from a dynamic language (don’t guess I’m phper), I’m used to using eval()
to think about Go dynamically executing code.
How golang
use eval()
function, php
, javascript
comes with this feature. Golang officially does not provide related libraries.
In the rich Go third-party ecosystem, there is really no relevant library found. I saw someone made a demo and posted it on the blog. I came to use it to change, and made a library, I hope that the majority of gopher
is satisfied.
installation
$ go get github.com/PaulXu-cn/goeval
Features
This goeval library, pass in the golang
code string, and then execute the eval()
function, you can get the string code output to
stdout
.
Examples of use:
package main
import (
"fmt"
"github.com/PaulXu-cn/goeval"
)
func main() {
if re, err := goeval.Eval(
"",
"fmt.Print(\"Hello World! itjsz.com\")",
"fmt"); nil == err {
fmt.Print(string(re))
} else {
fmt.Print(err.Error())
}
}
Output:
Hello World! itjsz.com
Here we introduce the goeval
package, call its Eval function, the first parameter is the structure definition code (because there is no useful custom structure in the code, so pass empty here), the second string is the code to be executed , The third and subsequent strings are imported packages.
Implementation rules
- Construct the entire string of running code according to the incoming string
- Formatting code is mainly to delete unused packages, so there can be more packages of
import
- Create a random directory under the
tmp
main.go
file in the newly created directory- Write formatted code
- Run
go run main.go
and collectstdout
- Delete the created folder and
main.go
- Return stdout
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。