Skip to content

Instantly share code, notes, and snippets.

@KentaKudo
Last active May 4, 2018 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KentaKudo/9e6f2acc2fded682622bb6eaf1bd366e to your computer and use it in GitHub Desktop.
Save KentaKudo/9e6f2acc2fded682622bb6eaf1bd366e to your computer and use it in GitHub Desktop.
Try out go plugin package
package main
import (
"fmt"
)
// F is to be loaded and called from main().
func F() {
fmt.Println(`This is a function in "a.go"`)
}
package main
import "fmt"
// F is to be loaded and called from main().
func F() {
fmt.Println(`This is a function "b.go"`)
}
package main
import (
"fmt"
"os"
"plugin"
)
func main() {
if len(os.Args) < 2 {
fmt.Println(help())
os.Exit(1)
}
p, err := plugin.Open(os.Args[1] + ".so")
if err != nil {
fmt.Fprintf(os.Stderr, "Unexpected command: %s", err)
os.Exit(1)
}
f, err := p.Lookup("F")
if err != nil {
fmt.Fprintf(os.Stderr, "Function F not found: %s", err)
os.Exit(1)
}
f.(func())()
}
func help() string {
return ""
}
@KentaKudo
Copy link
Author

KentaKudo commented May 4, 2018

  1. build a.go and b.go with plugin mode
$ go build -buildmode=plugin a.go
$ go build -buildmode=plugin b.go
  1. build main.go
$ go build main.go
  1. run main with arguments
$ ./main a
This is a function in "a.go"
$ ./main b
This is a function in "b.go"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment