Demo project showing how to use Yaegi to load and execute Go code at runtime.
English | 中文
The HTTP handler is defined in rule/rule.go and hot-reloaded by Yaegi.
- Go 1.22+
Start the demo server:
make runSend a request:
curl localhost:8080 -iExample response (truncated):
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Type: text/plain; charset=utf-8
Via: useless-helper
Date: Thu, 23 Nov 2023 12:24:31 GMT
Content-Length: 241
Hello!
Your Content-Type is
Your User-Agent is curl/8.1.2
Your Host is localhost:8080
Your RemoteAddr is 127.0.0.1:61784
Your RequestURI is /
Your Method is GET
Your Proto is HTTP/1.1
Your URL is /
Code above is wrote by GitHub Copilot.
:)Edit rule/rule.go and save; the server response updates without restart.
--rule(default:./rule/rule.go): rule file path
make generate: regenerate Yaegi symbolsmake build: build binary intooutput/yaegi_demo
To call host-compiled functions from the script:
- Add a function to a host package (for example
internal/helper). - Register that package in
internal/symbol/symbol.govia a//go:generate yaegi extract <module path>line. - Run
make generateto refresh Yaegi symbols. - Import and call it from
rule/rule.go.
Under the hood, yaegi extract generates files like internal/symbol/github_com-dcjanus-yaegi_demo-internal-helper.go.
These files define the external symbols the engine can load, and only registered symbols can be used in rule/rule.go.
Example (already in this repo):
// rule/rule.go
import "github.com/dcjanus/yaegi_demo/internal/helper"
// ...
helper.UselessHelper(w, helper.UselessHeader).
├── cmd
│ └── main.go # Program entry
├── internal
│ ├── engine # Yaegi execution & reload
│ ├── helper # Demo helpers
│ └── symbol # Interpreter symbols
├── rule
│ └── rule.go # Hot-reloaded handler
├── Makefile # Dev commands
├── README.md # Project overview
├── README.zh_CN.md # Chinese README
├── go.mod # Module definition
└── go.sum # Dependency checksums