SoFunction
Updated on 2025-03-01

Golang's dry goods sharing: using AST to realize AOP function

Brief description

This article is all simple and practical information, which directly lets us know how to implement an AOP function. In this example, we define a name calledMyStruct, it has two fields and two methods. Then, we use Golang's AST package to iterate through the source code's AST and find the nameMyStructstructure method.

For each method, we create a new log statement and insert it at the beginning of the method body. In this way, when the method is called, a log message will be automatically printed.

Finally, we use Golang'sThe function outputs the newly generated AST node as Go code.

Hopefully this example helps you understand how to implement AOP using Golang's AST package.

Sample code

package main

import (
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"log"
	"os"
)

func main() {
	src := `package main

type MyStruct struct {
	Field1 int
	Field2 string
}

func (m *MyStruct) Method1() {
	println(m.Field1)
}

func (m *MyStruct) Method2() {
	println(m.Field2)
}
`
	fset := ()
	f, err := (fset, "", src, 0)
	if err != nil {
		(err)
	}

	(f, func(n ) bool {
		switch x := n.(type) {
		case *:
			if  != nil && len() == 1 && [0].Names[0].Name == "m" && [0].Type.(*).X.(*).Name == "MyStruct" {

				logStmt := &{
					X: &{
						Fun: &{
							X:   ("log"),
							Sel: ("Println"),
						},
						Args: []{&{
							ValuePos: (),
							Kind:     ,
							Value:    "\"Entering " +  + "\"",
						}},
					},
				}

				 = append([]{logStmt}, ...)
				return false
			}

		}
		return true
	})

	(, fset, f)
}


//-----------------------------------------------------------------------------------------------------------------------------package main

type MyStruct struct {
	Field1	int
	Field2	string
}

func (m *MyStruct) Method1() {
	("Entering Method1")
	println(m.Field1)
}

func (m *MyStruct) Method2() {
	("Entering Method2")
	println(m.Field2)
}

This is the article about sharing Golang's dry information and using AST to implement AOP functions. For more related content on Golang AST to implement AOP, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!