Go Extensions (CGO and Plugins)
Most of the time, Go's standard library and the vast ecosystem of Go packages are enough. However, sometimes you need to call code written in C or load a Go plugin at runtime.
1. CGO: Calling C Code
CGO allows your Go program to call C functions. This is useful for using legacy C libraries (like zlib or OpenSSL).
Note: CGO makes your code harder to compile and slower. Only use it when there is no pure Go alternative.
2. Go Plugins
Plugins allow you to load shared libraries (.so files) while your program is running. This is great for apps with a "modular" architecture (like a web server that loads new handlers without restarting).
plugin.go (The module)
Compile with:go build -buildmode=plugin -o greet.so plugin.go
main.go (The loader)
3. WebAssembly (WASM)
Go can also be compiled to WebAssembly to run in a web browser.
Why use Extensions?
- Reuse: Leverage millions of lines of existing C code.
- Performance: C can still be faster for certain math-heavy or low-level tasks.
- Extensibility: Let users write their own logic and plug it into your application at runtime.