Skip to content

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).

package main

/*
// This is C code inside a comment block
#include <stdio.h>

void hello() {
    printf("Hello from C!\n");
}
*/
import "C"

func main() {
    // Call the C function defined above
    C.hello()
}

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)

1
2
3
4
5
package main

func Greet() string {
    return "Hello from Plugin!"
}
Compile with: go build -buildmode=plugin -o greet.so plugin.go

main.go (The loader)

1
2
3
4
5
p, _ := plugin.Open("greet.so")
symbol, _ := p.Lookup("Greet")
greetFunc := symbol.(func() string)

fmt.Println(greetFunc())

3. WebAssembly (WASM)

Go can also be compiled to WebAssembly to run in a web browser.

GOOS=js GOARCH=wasm go build -o main.wasm main.go

Why use Extensions?

  1. Reuse: Leverage millions of lines of existing C code.
  2. Performance: C can still be faster for certain math-heavy or low-level tasks.
  3. Extensibility: Let users write their own logic and plug it into your application at runtime.