goinject is a wrapper library for creating Go preprocessors.
goinject allows you to create custom preprocessors by defining a struct that satisfies the Modifier interface. This interface has only one method, Modify, which accepts a (*dst.File, *decorator.Decorator, *decorator.Restorer) representing the AST of a Go source file, file decorator and imports restorer. This method must return a modified *dst.File.
The goinject.Process function represents the generalized approach to preprocessing Go code. It performs the following steps:
- Checks if we are at the right stage of compilation.
- If not, runs the original command and returns.
- Extracts the files that Go is about to compile.
- Makes changes to the AST of all the files (without modifying the original source code).
- Writes the modified files to a temporary directory.
- Resolves all missing imports that were added as part of the modification.
- Substitutes the path to the original files with the path to the modified files and passes them to the compiler command.
- Runs the original command with the substituted files to be compiled.
Here's an example of how you can use goinject to modify a Go source file:
package main
import (
"github.com/pijng/goinject"
)
// CustomModifier implements the Modifier interface
type CustomModifier struct{}
// Modify implements the Modify method of the Modifier interface
func (cm CustomModifier) Modify(f *dst.File, dec *decorator.Decorator, res *decorator.Restorer) *dst.File {
// Add custom modification logic here
return f
}
func main() {
// Call goinject.Process with an instance of your modifier struct
goinject.Process(CustomModifier{})
}In this example, CustomModifier is a struct that satisfies the Modifier interface. It implements the Modify method, where you can define your custom modification logic.
goinject makes newly added imports visible to the compiler of the modified package, but it does not change the linker's dependency graph. Every package your modifications import must already be a dependency of the final binary, otherwise linking fails with cannot find package <pkg> (using -importcfg). The usual way to guarantee this is a blank import in the target's main package:
import _ "github.com/you/your-preprocessor-runtime"- go_otel_auto_instrument:
go_otel_auto_instrumentis a preprocessor that automatically inject Opentelemtry tracing into your Go code. - prep:
prepis a small Go tool that enables compile-time function evaluation. - go-ifdef:
go-ifdefis a preprocessor that allows you to use trivial#ifdefand#elsedirectives based on the GOOS environment variable.