go-ql
is a Go library for analyzing and extracting AST and type information from Go source code.
It uses static analysis to query AST nodes like statements and call expr, adding criterias that is intuitive, making it ideal for extract information from go code.
- Static Analysis: Extracts API route details from Go source code.
- Flexible Queries: Supports flexible filtering in various ways.
- Query-Based Extraction: Capture on match
go get github.com/xhd2015/go-ql@latest
Below is a minimal example demonstrating core usage by analyzing routes in a specified directory.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/xhd2015/go-ql/engine"
"github.com/xhd2015/go-ql/ql"
"github.com/xhd2015/go-ql/types"
)
type MatchResult struct {
Method string
API string
Handler string
File string
}
func main() {
// Define the directory to analyze
dir := "./test/testdata/route/basic"
// Load Go packages
pkgs, err := engine.LoadPackagesTypeInfo(dir, "./...")
if err != nil {
fmt.Printf("Failed to load packages: %v\n", err)
os.Exit(1)
}
// Define the query for API routes
// find call like:
// r.Any("/api/ping", handler.Gin(PingHandler))
q := ql.Select(ql.CallStmt()).
Where(
ql.CallStmt().Func().Name().In("Any", "GET", "POST", "PUT", "DELETE", "PATCH").Capture("method"),
ql.CallStmt().Func().Receiver().IsNonNil(),
ql.CallStmt().Args(0).AsLiteral().Capture("api"),
ql.CallStmt().Args(1).AsCall().Func().Name().Eq("Gin"),
ql.CallStmt().Args(1).AsCall().Args(0).Capture("handler"),
ql.CallStmt().Capture("callStmt").File().Capture("file"),
)
// Execute the query
matches, err := engine.Execute(pkgs, q)
if err != nil {
fmt.Printf("Query failed: %v\n", err)
os.Exit(1)
}
// Collect results
var results []MatchResult
for _, match := range matches {
file, _ := match.Captures["file"].(*types.File)
tokenFile := pkgs.Fset.File(file.Ast.Pos())
results = append(results, MatchResult{
Method: fmt.Sprintf("%v", match.Captures["method"]),
API: fmt.Sprintf("%v", match.Captures["api"]),
Handler: fmt.Sprintf("%v", match.Captures["handler"])
File: filepath.Base(tokenFile.Name()),
})
}
// Print results
fmt.Println("API Routes Found:")
for _, result := range results {
fmt.Printf("- %s %s (File: %s)\n", result.Method, result.API, result.File)
}
}
- Load Packages: The code loads Go packages from the specified directory using
engine.LoadPackagesTypeInfo
. - Query Routes: A query is defined using
ql.Select
to extract API routes with HTTP methods (e.g., GET, POST) and their paths. - Execute and Display: The query is executed, and results (method, API path, and file) are printed.
API Routes Found:
- GET /api/user/profile (File: basic.go)
- POST /api/user/update (File: basic.go)
-
Clone the repository:
git clone https://github.com/xhd2015/go-ql cd go-ql
-
Run the example:
go run .
Check ./test for more details.
Fork the repository, create a branch, make changes, and submit a pull request. Ensure code follows project standards.
MIT License. See LICENSE for details.
Open an issue on GitHub for questions or support.