How to use non-main package as plugin?

Hi guys, I want to compile non-main packages into plugin, but currently Go only supports compiling main packages (other packages will have invalid ELF header error) for plugin mode. Is there any workaround or tricks can achieve my goal, or any suggestions?

So my first question would be why you want your plugins to be non-main packages? This implies you want them to be imported somewhere, but plugins are intended to be standalone. Any shared API/interface should be defined in a shared package that they all import.

Plugins are still kind of new and relatively unused/unexploited, so best practices are still developing, but I think that your best bet is having a separate package that represents the common interfaces for all of your plugins. I took a crack at this a few months ago: https://github.com/alaska/golang-plugin-example

In my example, the “extern” package (I would probably call it “common” or “pluginbase” now) represents all of the shared code, and then it’s imported by the main binary as well as each of the plugins.

This way, anyone looking to make their own plugins for the project only needs to

import (
    "github.com/alaska/golang-plugin-example/extern"
    //whatever else they need
)

And it’s off to the races.

In my example, I use functions, but you could just as easily use shared interface types, similar to Vladimir Vivien’s example, though I would probably still choose to put the interfaces into a shared package and then explicitly declare an importable variable of the shared interface type to force compliance with the type system.

I have just such an example sitting around in a branch that I should really get around to pushing, so let me know if that would be helpful to you.

EDIT: Updated to fix import

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.