### Quick Start Build and Run Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Perform an instrumented build and execution without manual setup. ```bash # Build (no init required) whatap-go-inst go build ./... # Run ./myapp # or whatap-go-inst go run . ``` -------------------------------- ### Install whatap-go-inst via Binary Source: https://github.com/whatap/go-api-inst/blob/main/README.md Download and install the pre-built binary for Linux systems. ```bash # Linux amd64 curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ # Linux arm64 curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_arm64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ # Specific version (e.g., v0.5.4) curl -sSL https://github.com/whatap/go-api-inst/releases/download/v0.5.4/whatap-go-inst_linux_amd64.tar.gz | tar xz ``` -------------------------------- ### Full Configuration Example Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md A comprehensive example showing injection, replacement, hooking, and file addition. ```yaml # .whatap/config.yaml instrumentation: preset: minimal debug: true custom: # Logging at function start inject: - package: "main" function: "Handle*" start: | log.Printf("[%s] started", "{{.FuncName}}") imports: - "log" # Replace sql.Open replace: - package: "database/sql" function: "Open" with: "whatapsql.Open" imports: - "github.com/whatap/go-api/instrumentation/database/sql/whatapsql" # Trace specific function calls hook: - package: "main" function: "processOrder" before: | trace.Step(ctx, "ORDER", "processOrder started") after: | trace.Step(ctx, "ORDER", "processOrder completed") imports: - "github.com/whatap/go-api/trace" # Create helper file add: - package: "main" file: "whatap_init.go" content: | package main import "github.com/whatap/go-api/trace" func init() { trace.Init(nil) } ``` -------------------------------- ### Install via go install Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Install the tool using the Go toolchain for versions 1.21 or higher. ```bash # Official binary go install github.com/whatap/go-api-inst/cmd/whatap-go-inst@latest # Short binary name go install github.com/whatap/go-api-inst/cmd/goinst@latest ``` -------------------------------- ### Install whatap-go-inst via Go Source: https://github.com/whatap/go-api-inst/blob/main/README.md Install the tool directly using the Go toolchain. ```bash go install github.com/whatap/go-api-inst/cmd/whatap-go-inst@latest ``` -------------------------------- ### Install WhaTap Go Instrumentation Source: https://context7.com/whatap/go-api-inst/llms.txt Commands to download, install, or build the instrumentation tool from source. ```bash # Linux amd64 - Download binary (Recommended) curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ # Linux arm64 curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_arm64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ # Specific version (e.g., v0.5.4) curl -sSL https://github.com/whatap/go-api-inst/releases/download/v0.5.4/whatap-go-inst_linux_amd64.tar.gz | tar xz # Go Install (Go 1.21+) go install github.com/whatap/go-api-inst/cmd/whatap-go-inst@latest # Build from source git clone https://github.com/whatap/go-api-inst cd go-api-inst go build -o whatap-go-inst . # Verify installation whatap-go-inst version ``` -------------------------------- ### Install whatap-go-inst (Linux amd64) Source: https://github.com/whatap/go-api-inst/blob/main/docs/README.md Installs the whatap-go-inst binary on Linux amd64 systems. This is a prerequisite for using the build wrapper mode. ```bash # Install (Linux amd64) curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ ``` -------------------------------- ### Install via Direct Binary Download Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Download and install the binary for Linux systems. ```bash # Linux (amd64) curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ # Linux (arm64) curl -sSL https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_arm64.tar.gz | tar xz sudo mv whatap-go-inst /usr/local/bin/ ``` -------------------------------- ### Verify Installation Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Check the installed version of the tool. ```bash whatap-go-inst version # Or short command goinst version ``` -------------------------------- ### Build Go Project with Build Wrapper Source: https://github.com/whatap/go-api-inst/blob/main/docs/README.md Builds a Go project using the installed whatap-go-inst binary. This method does not require manual initialization and is the recommended approach for instrumentation. ```bash # Build (no init required) whatap-go-inst go build ./... ``` -------------------------------- ### Docker Build Integration Source: https://github.com/whatap/go-api-inst/blob/main/README.md Example Dockerfile demonstrating how to build an instrumented Go application and run it with the WhaTap agent. ```dockerfile # Stage 1: Build with instrumentation FROM golang:1.21-alpine AS builder # Install whatap-go-inst RUN wget -qO- https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz -C /usr/local/bin/ WORKDIR /app COPY . . # Build with instrumentation RUN whatap-go-inst go build -o /app/server . # Stage 2: Run with WhaTap agent FROM alpine:latest # Install WhaTap agent RUN wget -qO- https://s3.ap-northeast-2.amazonaws.com/repo.whatap.io/alpine/x86_64/whatap-agent.tar.gz | tar xz -C / WORKDIR /app COPY --from=builder /app/server . # Create WhaTap config file RUN echo "license=your-license-key" > whatap.conf && \ echo "whatap.server.host=13.124.11.223" >> whatap.conf && \ echo "app_name=myapp" >> whatap.conf ENV WHATAP_HOME=/app EXPOSE 8080 CMD ["/bin/sh", "-c", "/usr/whatap/agent/whatap-agent start && ./server"] ``` -------------------------------- ### Build Wrapper Examples Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Common usage patterns for the build wrapper, including error tracking and output configuration. ```bash # Build entire project whatap-go-inst go build ./... # Specify output file whatap-go-inst go build -o myapp . # Run directly whatap-go-inst go run . # Run tests whatap-go-inst go test ./... # Build with error tracking code whatap-go-inst --error-tracking go build ./... # Disable instrumented source output whatap-go-inst --no-output go build ./... # Save instrumented source to custom path whatap-go-inst --output ./instrumented go build ./... # Instrument external module from GOMODCACHE whatap-go-inst --external-module=mycompany.com/internal/lib go build ./... ``` -------------------------------- ### Instrumentation Example Source Code Source: https://github.com/whatap/go-api-inst/blob/main/docs/build-wrapper.md Comparison of original source code and the resulting code after instrumentation. ```go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello"}) }) r.Run(":8080") } ``` ```bash whatap-go-inst go build -o myapp . ``` ```go package main import ( "github.com/gin-gonic/gin" "github.com/whatap/go-api/trace" "github.com/whatap/go-api/instrumentation/github.com/gin-gonic/gin/whatapgin" ) func main() { trace.Init(nil) defer trace.Shutdown() r := gin.Default() r.Use(whatapgin.Middleware()) r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello"}) }) r.Run(":8080") } ``` -------------------------------- ### Context Preservation: Using Context with SQL Open Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/common.md This example highlights the preferred method of passing a `context.Context` to `whatapsql.OpenContext` for efficient tracing. ```go // GOOD: Pass context whatapsql.OpenContext(ctx, driverName, dataSourceName) ``` -------------------------------- ### Dockerfile for Instrumented Build Source: https://github.com/whatap/go-api-inst/blob/main/docs/build-wrapper.md Multi-stage Dockerfile setup to build an instrumented Go binary and run it with the WhaTap agent. ```dockerfile # Stage 1: Build with instrumentation FROM golang:1.21-alpine AS builder # Install whatap-go-inst RUN wget -qO- https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz -C /usr/local/bin/ WORKDIR /app COPY . . # Build with instrumentation RUN whatap-go-inst go build -o /app/server . # Stage 2: Run with WhaTap agent FROM alpine:latest # Install WhaTap agent RUN wget -qO- https://s3.ap-northeast-2.amazonaws.com/repo.whatap.io/alpine/x86_64/whatap-agent.tar.gz | tar xz -C / WORKDIR /app COPY --from=builder /app/server . # WhaTap config RUN echo "license=your-license-key" > whatap.conf && \ echo "whatap.server.host=13.124.11.223" >> whatap.conf && \ echo "app_name=myapp" >> whatap.conf ENV WHATAP_HOME=/app EXPOSE 8080 CMD ["/bin/sh", "-c", "/usr/whatap/agent/whatap-agent start && ./server"] ``` -------------------------------- ### Add Middleware Transformation Example Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Injects middleware into a Gin router initialization. ```yaml custom: transform: - package: "github.com/gin-gonic/gin" function: "Default" template: | {{.Original}} {{.Var}}.Use(whatapgin.Middleware()) imports: - "github.com/whatap/go-api/instrumentation/github.com/gin-gonic/gin/whatapgin" ``` ```go // Before r := gin.Default() // After r := gin.Default() r.Use(whatapgin.Middleware()) ``` -------------------------------- ### Initialize WhaTap Trace in main() Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Initialize the WhaTap trace functionality at the beginning of your main function and ensure it is shut down gracefully using defer. This is essential for WhaTap to start collecting data. ```go func main() { trace.Init(nil) defer trace.Shutdown() // Original code... } ``` -------------------------------- ### Injected Web Framework Middleware Source: https://github.com/whatap/go-api-inst/blob/main/README.md Examples of how various web frameworks are instrumented with middleware or wrappers. ```go // Gin r := gin.Default() r.Use(whatapgin.Middleware()) // Auto-injected // Echo v4 e := echo.New() e.Use(whatapecho.Middleware()) // Auto-injected // Fiber v2 app := fiber.New() app.Use(whatapfiber.Middleware()) // Auto-injected // Chi (in-place wrapping) r := whatapchi.WrapRouter(chi.NewRouter()) // Gorilla Mux (in-place wrapping) r := whatapmux.WrapRouter(mux.NewRouter()) // net/http (handler wrapping) mux.HandleFunc("/", whataphttp.Func(handler)) // Auto-wrapped mux.Handle("/api", whataphttp.WrapHandler(h)) // Auto-wrapped ``` -------------------------------- ### External Module Output Structure Source: https://context7.com/whatap/go-api-inst/llms.txt Example directory structure resulting from external module instrumentation. ```text ./instrumented/ ├── main.go (instrumented) ├── go.mod (replace directive added) └── _modules/ └── mycompany/ └── db-lib/ ├── connection.go (instrumented) └── go.mod (whatap/go-api require added) ``` -------------------------------- ### Log Collection Settings Example Source: https://github.com/whatap/go-api-inst/blob/main/docs/config.md Logging library instrumentation, including AST instrumentation, is typically included in the 'log' or 'full' presets within the Whatap configuration. ```text Logging library instrumentation is included in the `log` preset (and `full` preset). ``` -------------------------------- ### Context Preservation: Avoiding Goroutine ID Fallback Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/common.md This example shows the less preferred method of calling `whatapsql.Open` without a context, which forces a fallback to goroutine ID extraction. ```go // AVOID: Call without context (goroutine ID fallback used) whatapsql.Open(driverName, dataSourceName) ``` -------------------------------- ### Build whatap-go-inst from Source Source: https://github.com/whatap/go-api-inst/blob/main/README.md Clone the repository and build the binary locally. ```bash git clone https://github.com/whatap/go-api-inst cd go-api-inst go build -o whatap-go-inst . ``` -------------------------------- ### Initialize and Shutdown Trace Package in main() Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/common.md Demonstrates how to initialize the Whatap trace package at the beginning of your main function and ensure it's shut down gracefully using defer. ```go func main() { trace.Init(nil) // Inserted defer trace.Shutdown() // Inserted // ... existing code } ``` -------------------------------- ### Handle Instrumentation Errors Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Example of a fail-fast error message during the instrumentation process. ```text Error: main.go: apply custom rules: inject rules: 3:6: expected ';', found is ``` -------------------------------- ### Hook Transformation Result Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Example of code modification after applying a hook rule. ```go // Before data := fetchData() // After fmt.Println(">>> fetchData starting") data := fetchData() fmt.Println("<<< fetchData completed") ``` -------------------------------- ### Build and Run Commands with whatap-go-inst Source: https://github.com/whatap/go-api-inst/blob/main/docs/build-wrapper.md Commands for building, running, and testing Go applications with automatic instrumentation. ```bash # Build (no init required) whatap-go-inst go build ./... ``` ```bash # Build all packages whatap-go-inst go build ./... # Specify output file whatap-go-inst go build -o myapp . # Disable instrumented source output whatap-go-inst --no-output go build ./... # Save instrumented source to custom path whatap-go-inst --output ./instrumented go build ./... ``` ```bash whatap-go-inst go run . whatap-go-inst go run . --port 8080 ``` ```bash whatap-go-inst go test ./... whatap-go-inst go test -v -run TestName ./pkg/... ``` -------------------------------- ### Replace Transformation Result Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Example of code modification after applying a replace rule. ```go // Before db, err := sql.Open("mysql", dsn) // After db, err := whatapsql.Open("mysql", dsn) ``` -------------------------------- ### Use Build Wrapper Source: https://github.com/whatap/go-api-inst/blob/main/README.md Prefix standard Go commands with the instrumentation tool to apply monitoring during build or execution. ```bash # Build (no init required) whatap-go-inst go build ./... whatap-go-inst go build -o myapp . # Run whatap-go-inst go run . # Test whatap-go-inst go test ./... ``` -------------------------------- ### Inject Transformation Result Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Example of code modification after applying an inject rule. ```go // Before func ProcessData(data string) error { return process(data) } // After func ProcessData(data string) error { fmt.Println("function started") return process(data) fmt.Println("function ended") // Warning: unreachable - use defer } ``` -------------------------------- ### Configure Inject Rule Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Inserts code at the start or end of function definitions. ```yaml custom: inject: - package: "main" # Package name (package declaration in file) function: "Process*" # Function name pattern (wildcards supported) start: | # Insert at function start fmt.Println("function started") end: | # Insert at function end (note: after return) fmt.Println("function ended") imports: # Required imports - "fmt" ``` -------------------------------- ### JSON Report Structure Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Example of the JSON output format generated by the report option. ```json { "timestamp": "2026-01-07T15:00:00+09:00", "command": "inject", "summary": { "total": 10, "instrumented": 3, "skipped": 2, "copied": 5, "errors": 0 }, "files": [ { "path": "main.go", "status": "instrumented", "transformers": ["gin"], "changes": ["added import: whatapgin", "added: trace.Init"] } ] } ``` -------------------------------- ### Multi-Stage Docker Build with Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/multi-module.md This Dockerfile demonstrates a multi-stage build process. The first stage builds the application with whatap-go-inst, including external module instrumentation. The second stage sets up the runtime environment with the WhaTap agent and the built binary. ```dockerfile # Stage 1: Build with instrumentation FROM golang:1.21-alpine AS builder # Install whatap-go-inst RUN wget -qO- https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz -C /usr/local/bin/ WORKDIR /app COPY . . # Build with external module instrumentation RUN go mod download RUN whatap-go-inst \ --external-module="mycompany.com/*" \ go build -o /app/server ./... # Stage 2: Runtime FROM alpine:latest # Install WhaTap agent RUN wget -qO- https://s3.ap-northeast-2.amazonaws.com/repo.whatap.io/alpine/x86_64/whatap-agent.tar.gz | tar xz -C / WORKDIR /app COPY --from=builder /app/server . # WhaTap config RUN echo "license=your-license-key" > whatap.conf && \ echo "whatap.server.host=13.124.11.223" >> whatap.conf && \ echo "app_name=myapp" >> whatap.conf ENV WHATAP_HOME=/app EXPOSE 8080 CMD ["/bin/sh", "-c", "/usr/whatap/agent/whatap-agent start && ./server"] ``` -------------------------------- ### Cobra Command Initialization with Gin Middleware Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/common.md Illustrates the transformation of a Cobra command's Run function to include Whatap's Gin middleware for tracing HTTP requests. ```go // Before var serverCmd = &cobra.Command{ Use: "server", Run: func(cmd *cobra.Command, args []string) { r := gin.New() // Detected and transformed r.Run(":8080") }, } // After var serverCmd = &cobra.Command{ Use: "server", Run: func(cmd *cobra.Command, args []string) { r := gin.New() r.Use(whatapgin.Middleware()) // Inserted r.Run(":8080") }, } ``` -------------------------------- ### Build from Source Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Compile the tool directly from the repository source code. ```bash git clone https://github.com/whatap/go-api-inst.git cd go-api-inst go build -o whatap-go-inst . ``` -------------------------------- ### Configure whatap-go-inst via YAML Source: https://github.com/whatap/go-api-inst/blob/main/docs/config.md The standard configuration file format for defining instrumentation settings, package selection, and exclusion patterns. ```yaml # .whatap/config.yaml instrumentation: # Basic options error_tracking: false # Inject error tracking code (--error-tracking) debug: false # Enable debug output (GO_API_AST_DEBUG) output_dir: "" # Instrumented source output directory # Package selection preset: "full" # Instrumentation preset (full/minimal/web/database/external/log/custom) enabled_packages: [] # Additional packages to enable disabled_packages: [] # Packages to disable # User-defined instrumentation — see custom-instrumentation.md # custom: # inject: [] # replace: [] # hook: [] # transform: [] # External modules to instrument from GOMODCACHE # external_modules: # - "mycompany.com/internal/lib" # File patterns to exclude (optional - defaults auto-applied if omitted) # exclude: # - "*_test.go" # - "vendor/**" ``` -------------------------------- ### Build Wrapper Syntax Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md General syntax for using the build wrapper to instrument Go commands. ```bash whatap-go-inst [global-options] go [arguments] ``` -------------------------------- ### Build Single Module Project Source: https://github.com/whatap/go-api-inst/blob/main/docs/multi-module.md For new projects structured as a single module, use the standard build command with whatap-go-inst. No special flags are needed for basic instrumentation. ```bash whatap-go-inst go build ./cmd/main ``` -------------------------------- ### Transform Aerospike Get Call Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/external-services.md Wraps aerospike.Get calls using whatapsql.Wrap for instrumentation, as Aerospike does not support direct hooks. Only v6 and v8 are supported. ```go // Before record, err := client.Get(policy, key) ``` ```go // After record, err := whatapsql.Wrap(context.Background(), "aerospike", "Get", func() (*aerospike.Record, error) { return client.Get(policy, key) }) ``` -------------------------------- ### Ensure Whatap Dependency Propagation Source: https://github.com/whatap/go-api-inst/blob/main/docs/multi-module.md Modules that depend on instrumented libraries must also include the whatap dependency. Add it using 'go get'. ```bash cd main-app go get github.com/whatap/go-api@latest ``` -------------------------------- ### Source Code Before and After Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/source-inject.md Comparison of a standard Gin application before and after the automatic injection of WhaTap middleware. ```go package main import ( "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello"}) }) r.Run(":8080") } ``` ```go package main import ( "github.com/gin-gonic/gin" "github.com/whatap/go-api/instrumentation/github.com/gin-gonic/gin/whatapgin" "github.com/whatap/go-api/trace" ) func main() { trace.Init(nil) defer trace.Shutdown() r := gin.Default() r.Use(whatapgin.Middleware()) // Middleware auto-injected r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello"}) }) r.Run(":8080") } ``` -------------------------------- ### Build with Auto Injection Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md After cleaning up manual instrumentation and verifying changes, use the `whatap-go-inst go build` command to build your application with auto-instrumentation enabled. ```bash # 4. Build with auto injection whatap-go-inst go build ./... ``` -------------------------------- ### Instrument Empty http.Client Initialization Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/web-frameworks.md Adds a Whatap RoundTripper to an empty http.Client, enabling instrumentation and context propagation. ```go // Before client := &http.Client{ Timeout: 10 * time.Second, } // After (marker function - Transport field removed on remove, handler context auto-detected) client := &http.Client{ Timeout: 10 * time.Second, Transport: whataphttp.NewRoundTripWithEmptyTransport(c.Request.Context()), } ``` -------------------------------- ### Complete Instrumentation Workflow Source: https://github.com/whatap/go-api-inst/blob/main/docs/source-inject.md Standard sequence for injecting, verifying, and building the instrumented project. ```bash whatap-go-inst inject -s ./myapp -o ./instrumented ``` ```bash diff myapp/main.go instrumented/main.go ``` ```bash cd instrumented go get github.com/whatap/go-api@latest go mod tidy go build -o ../myapp . ``` -------------------------------- ### Inject Instrumentation into Go Source Code Source: https://github.com/whatap/go-api-inst/blob/main/docs/README.md Modifies Go source files directly by injecting instrumentation code. This creates a new 'instrumented' directory and requires running 'go get' and 'go build' within that directory. ```bash whatap-go-inst inject -s ./myapp -o ./instrumented cd instrumented && go get github.com/whatap/go-api@latest && go build . ``` -------------------------------- ### Instrument database/sql Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/database.md Use the whatapsql wrapper to track database operations like Query, Exec, and Prepare. ```go import "github.com/whatap/go-api/instrumentation/database/sql/whatapsql" ``` ```go // Before db, err := sql.Open("mysql", "user:pass@/dbname") // After db, err := whatapsql.Open("mysql", "user:pass@/dbname") ``` -------------------------------- ### Configure fmt Package Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/log.md Use whatapfmt to transform standard fmt print functions for transaction correlation. ```go import ( "fmt" "github.com/whatap/go-api/instrumentation/fmt/whatapfmt" ) func main() { trace.Init(nil) defer trace.Shutdown() whatapfmt.Println("Server starting...") // fmt.Println → whatapfmt.Println transformed } ``` -------------------------------- ### Enable whatapfmt Configuration Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/log.md Enable logsink and fmt instrumentation in the whatap.conf file. ```ini # whatap.conf logsink_enabled=true logsink_fmt_enabled=true # Enable whatapfmt ``` -------------------------------- ### Configure Standard log Package Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/log.md Use logsink.GetTraceLogWriter to wrap the output writer for standard log package integration. ```go import ( "log" "github.com/whatap/go-api/logsink" "os" ) func main() { trace.Init(nil) defer trace.Shutdown() log.SetOutput(logsink.GetTraceLogWriter(os.Stderr)) // Inserted // ... } ``` -------------------------------- ### Match Package Scope Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Demonstrates how the package field maps to Go source declarations. ```go package user // ← Matches this value ``` -------------------------------- ### Test Build Without whatap-go-inst Source: https://github.com/whatap/go-api-inst/blob/main/docs/troubleshooting.md Verify that your project builds correctly without any instrumentation by running a standard Go build command. ```bash # Test build without whatap-go-inst go build ./... ``` -------------------------------- ### Initialize Router in main() or init() Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Initializing web framework routers (like Gin) in global variables can lead to middleware not being auto-added. Initialize them within main() or init() functions instead. ```go // Middleware NOT auto-added var Router = gin.Default() // Global-level initialization ``` -------------------------------- ### net/http (Server) Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/web-frameworks.md Instructions for instrumenting the standard Go net/http server using Whatap's handler wrapping. ```APIDOC ## POST /api/config ### Description Updates the application configuration. ### Method POST ### Endpoint /api/config ### Parameters #### Request Body - **setting** (string) - Required - The name of the configuration setting to update. - **value** (any) - Required - The new value for the configuration setting. ### Request Example ```json { "setting": "timeout", "value": 30 } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the configuration was updated. #### Response Example ```json { "message": "Configuration updated successfully." } ``` ``` -------------------------------- ### Check Version Information Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Displays the current version of the whatap-go-inst tool. ```bash whatap-go-inst version ``` -------------------------------- ### Run WhaTap Go Instrumentation CLI Source: https://github.com/whatap/go-api-inst/blob/main/docs/custom-instrumentation.md Commands for running the instrumentation tool with various configuration and output options. ```bash # Default (auto-searches .whatap/config.yaml) whatap-go-inst inject -s . -o ./output ``` ```bash # Specify config file whatap-go-inst --config custom.yaml inject -s . -o ./output ``` ```bash # Environment variable WHATAP_INST_CONFIG=custom.yaml whatap-go-inst inject -s . -o ./output ``` ```bash # Verbose output whatap-go-inst inject -s . -o ./output -v ``` -------------------------------- ### Import WhaTap Kubernetes Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/external-services.md Required import for instrumenting Kubernetes client-go. ```go import "github.com/whatap/go-api/instrumentation/k8s.io/client-go/kubernetes/whatapkubernetes" ``` -------------------------------- ### Check Framework Versions and Debug Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/troubleshooting.md Verify framework versions in go.mod and enable debug mode to inspect instrumentation skip behavior. ```bash # Check framework version in go.mod grep -E "echo|fiber|go-redis|aerospike" go.mod # Debug mode to see skip behavior GO_API_AST_DEBUG=1 whatap-go-inst go build ./... ``` -------------------------------- ### Instrument net/http Server Source: https://context7.com/whatap/go-api-inst/llms.txt Wraps standard library handlers or server configurations with WhaTap instrumentation. ```go // Original code - HandleFunc and Handle http.HandleFunc("/api", apiHandler) http.Handle("/static", staticHandler) ``` ```go // After instrumentation http.HandleFunc("/api", whataphttp.Func(apiHandler)) http.Handle("/static", whataphttp.WrapHandler(staticHandler)) ``` ```go // http.Server struct literal pattern // Before s := &http.Server{ Addr: ":8080", Handler: mux, } ``` ```go // After s := &http.Server{ Addr: ":8080", Handler: whataphttp.WrapHandler(mux), } ``` -------------------------------- ### fmt (whatapfmt) Instrumentation Source: https://context7.com/whatap/go-api-inst/llms.txt Replaces the standard fmt.Println with whatapfmt.Println for instrumented logging. ```go // Before fmt.Println("Debug message") ``` ```go // After whatapfmt.Println("Debug message") ``` -------------------------------- ### Build Wrapper Mode Source: https://github.com/whatap/go-api-inst/blob/main/ReleaseNote.md Injects monitoring code and builds the project without modifying the original source files. ```bash whatap-go-inst go build ./... ``` -------------------------------- ### Transform Redis Client Creation (redis/go-redis v8/v9) Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/external-services.md Replaces calls to redis.NewClient with whatapgoredis.NewClient for instrumentation. Only v8 and v9 are supported. ```go // Before rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ``` ```go // After rdb := whatapgoredis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ``` -------------------------------- ### Injected main() Initialization Source: https://github.com/whatap/go-api-inst/blob/main/README.md Initialization and shutdown logic injected into the main function. ```go func main() { trace.Init(nil) defer trace.Shutdown() // ... existing code } ``` -------------------------------- ### Instrumenting with Docker Multi-stage Builds Source: https://context7.com/whatap/go-api-inst/llms.txt Integrate the instrumentation tool into a multi-stage Dockerfile to ensure monitoring is applied during the build process. ```dockerfile # Stage 1: Build with instrumentation FROM golang:1.21-alpine AS builder # Install whatap-go-inst RUN wget -qO- https://github.com/whatap/go-api-inst/releases/latest/download/whatap-go-inst_linux_amd64.tar.gz | tar xz -C /usr/local/bin/ WORKDIR /app COPY . . # Build with instrumentation (and external module if needed) RUN go mod download RUN whatap-go-inst go build -o /app/server . # Or with external module instrumentation # RUN whatap-go-inst --external-module="mycompany.com/*" go build -o /app/server ./... # Stage 2: Run with WhaTap agent FROM alpine:latest # Install WhaTap agent RUN wget -qO- https://s3.ap-northeast-2.amazonaws.com/repo.whatap.io/alpine/x86_64/whatap-agent.tar.gz | tar xz -C / WORKDIR /app COPY --from=builder /app/server . # Create WhaTap config file (get values from WhaTap Console) RUN echo "license=your-license-key" > whatap.conf && \ echo "whatap.server.host=13.124.11.223" >> whatap.conf && \ echo "app_name=myapp" >> whatap.conf ENV WHATAP_HOME=/app EXPOSE 8080 CMD ["/bin/sh", "-c", "/usr/whatap/agent/whatap-agent start && ./server"] ``` -------------------------------- ### Instrument go-redis Source: https://context7.com/whatap/go-api-inst/llms.txt Replaces Redis client creation with WhaTap-instrumented versions for v8/v9. ```go // Before (v9) rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // After rdb := whatapgoredis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // Cluster client // Before rdb := redis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"localhost:7000", "localhost:7001"}, }) // After rdb := whatapgoredis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"localhost:7000", "localhost:7001"}, }) // Failover client and Ring are also supported rdb := whatapgoredis.NewFailoverClient(&redis.FailoverOptions{...}) rdb := whatapgoredis.NewRing(&redis.RingOptions{...}) ``` -------------------------------- ### Build Wrapper Mode Commands Source: https://context7.com/whatap/go-api-inst/llms.txt Commands to wrap Go build and run operations for automatic instrumentation without modifying source files. ```bash # Build entire project with instrumentation whatap-go-inst go build ./... # Build with specific output file whatap-go-inst go build -o myapp . # Run directly with instrumentation whatap-go-inst go run . # Run tests with instrumentation whatap-go-inst go test ./... # Build with error tracking code injection whatap-go-inst --error-tracking go build ./... # Disable instrumented source output (default saves to whatap-instrumented/) whatap-go-inst --no-output go build ./... # Save instrumented source to custom path whatap-go-inst --output ./instrumented go build ./... # Instrument external module from GOMODCACHE whatap-go-inst --external-module=mycompany.com/internal/lib go build ./... # Multiple external modules with wildcard whatap-go-inst --external-module="mycompany.com/*" go build ./... # Debug mode GO_API_AST_DEBUG=1 whatap-go-inst go build ./... ``` -------------------------------- ### Basic Transformation Commands Source: https://github.com/whatap/go-api-inst/blob/main/docs/source-inject.md Various ways to invoke the injection tool, including directory-wide, single-file, and short-option variants. ```bash # Transform entire directory whatap-go-inst inject --src ./myapp --output ./instrumented # Transform single file whatap-go-inst inject --src ./myapp/main.go --output ./instrumented/main.go # Short options whatap-go-inst inject -s ./myapp -o ./instrumented # Default: src=".", output="./output" whatap-go-inst inject ``` -------------------------------- ### Instrument github.com/jmoiron/sqlx Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/database.md Replace standard sqlx connection methods with whatapsqlx to enable query tracking. ```go import "github.com/whatap/go-api/instrumentation/github.com/jmoiron/sqlx/whatapsqlx" ``` ```go // Before db, err := sqlx.Open("mysql", "user:pass@/dbname") db, err := sqlx.Connect("mysql", "user:pass@/dbname") db, err := sqlx.ConnectContext(ctx, "mysql", "user:pass@/dbname") db := sqlx.MustConnect("mysql", "user:pass@/dbname") db := sqlx.MustOpen("mysql", "user:pass@/dbname") // After db, err := whatapsqlx.Open("mysql", "user:pass@/dbname") db, err := whatapsqlx.Connect("mysql", "user:pass@/dbname") db, err := whatapsqlx.ConnectContext(ctx, "mysql", "user:pass@/dbname") db := whatapsqlx.MustConnect("mysql", "user:pass@/dbname") db := whatapsqlx.MustOpen("mysql", "user:pass@/dbname") ``` -------------------------------- ### Instrument github.com/jinzhu/gorm (Legacy) Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/database.md Use the legacy whatapgorm package for older versions of the GORM library. ```go import "github.com/whatap/go-api/instrumentation/github.com/jinzhu/gorm/whatapgorm" ``` ```go // Before db, err := gorm.Open("mysql", "user:pass@/dbname") // After db, err := whatapgorm.Open("mysql", "user:pass@/dbname") ``` -------------------------------- ### Use Local go-api for Development Source: https://github.com/whatap/go-api-inst/blob/main/docs/troubleshooting.md Configure your go.mod file to use a local copy of the go-api module for development purposes. ```go go mod edit -replace github.com/whatap/go-api=../go-api ``` -------------------------------- ### Instrument net/http Client Source: https://context7.com/whatap/go-api-inst/llms.txt Wraps HTTP client calls with context-aware tracing. Use the whataphttp package to replace standard http calls. ```go // Inside Gin handler - context auto-detected r.GET("/call-api", func(c *gin.Context) { // Before resp, err := http.Get("http://example.com/api") // After (uses c.Request.Context() automatically) resp, err := whataphttp.HttpGet(c.Request.Context(), "http://example.com/api") }) // Inside net/http handler func handler(w http.ResponseWriter, r *http.Request) { // Before resp, err := http.Get("http://example.com/api") // After (uses r.Context() automatically) resp, err := whataphttp.HttpGet(r.Context(), "http://example.com/api") } // Function with context parameter func fetchData(ctx context.Context, url string) { // Before resp, err := http.Get(url) // After (uses ctx directly) resp, err := whataphttp.HttpGet(ctx, url) } // http.DefaultClient methods // Before resp, err := http.DefaultClient.Get("http://example.com/api") resp, err := http.DefaultClient.Post("http://example.com/api", "application/json", body) // After resp, err := whataphttp.DefaultClientGet(ctx, "http://example.com/api") resp, err := whataphttp.DefaultClientPost(ctx, "http://example.com/api", "application/json", body) // http.Client initialization // Before client := &http.Client{Timeout: 10 * time.Second} // After client := &http.Client{ Timeout: 10 * time.Second, Transport: whataphttp.NewRoundTripWithEmptyTransport(ctx), } // With existing Transport // Before client := &http.Client{Transport: customTransport} // After client := &http.Client{Transport: whataphttp.NewRoundTrip(ctx, customTransport)} ``` -------------------------------- ### github.com/gin-gonic/gin Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/web-frameworks.md Instructions for instrumenting the Gin web framework using Whatap's middleware. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Configure zap Package Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/log.md Use logsink.HookStderr() to redirect zap output to WhaTap logsink. ```go import ( "go.uber.org/zap" "github.com/whatap/go-api/logsink" ) func main() { trace.Init(nil) defer trace.Shutdown() logsink.HookStderr() // Inserted logger, _ := zap.NewProduction() // ... } ``` -------------------------------- ### Instrument gorm.io/gorm Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/database.md Wrap the GORM Open call with whatapgorm to instrument database interactions. ```go import "github.com/whatap/go-api/instrumentation/github.com/go-gorm/gorm/whatapgorm" ``` ```go // Before db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) // After db, err := whatapgorm.Open(sqlite.Open("test.db"), &gorm.Config{}) ``` -------------------------------- ### Import WhaTap gRPC Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/external-services.md Required import for instrumenting gRPC server and client connections. ```go import "github.com/whatap/go-api/instrumentation/google.golang.org/grpc/whatapgrpc" ``` -------------------------------- ### Supported Frameworks Source: https://github.com/whatap/go-api-inst/blob/main/docs/user-guide.md Lists the web frameworks, databases, and other libraries that are supported by Whatap Go API instrumentation, along with the necessary import paths and instrumentation code. ```APIDOC ## Supported Frameworks ### Web Frameworks | Framework | Import Path | Injected Code | |-----------|-------------|---------------| | **Gin** | `github.com/gin-gonic/gin` | `r.Use(whatapgin.Middleware())` | | **Echo v4** | `github.com/labstack/echo/v4` | `e.Use(whatapecho.Middleware())` | | **Fiber v2** | `github.com/gofiber/fiber/v2` | `app.Use(whatapfiber.Middleware())` | | **Chi v5** | `github.com/go-chi/chi/v5` | `whatapchi.WrapRouter(chi.NewRouter())` | | **Gorilla Mux** | `github.com/gorilla/mux` | `whatapmux.WrapRouter(mux.NewRouter())` | | **net/http** | `net/http` | `whataphttp.Func()`, `whataphttp.WrapHandler()` | | **FastHTTP** | `github.com/valyala/fasthttp` | `whatapfasthttp.Middleware()` | > **Wrap Functions**: For struct field initialization and instance patterns, > framework-specific Wrap functions are available (e.g., `WrapEngine`, `WrapEcho`, `WrapApp`, `WrapRouter`, `WrapHandler`). > See [Instrumentation Rules](./rules/) for details. ### Database | Library | Import Path | Transformation | |---------|-------------|----------------| | **database/sql** | `database/sql` | `sql.Open()` → `whatapsql.Open()` | | **sqlx** | `github.com/jmoiron/sqlx` | `sqlx.Open()` → `whatapsqlx.Open()` | | **GORM (gorm.io)** | `gorm.io/gorm` | `gorm.Open()` → `whatapgorm.Open()` | | **GORM (jinzhu)** | `github.com/jinzhu/gorm` | `gorm.Open()` → `whatapgorm.Open()` | ### Redis | Library | Import Path | Transformation | |---------|-------------|----------------| | **go-redis v9** | `github.com/redis/go-redis/v9` | `redis.NewClient()` → `whatapgoredis.NewClient()` | | **go-redis v8** | `github.com/redis/redis/v8` | `redis.NewClient()` → `whatapgoredis.NewClient()` | | **Redigo** | `github.com/gomodule/redigo` | `redis.Dial()` → `whatapredigo.Dial()` | ### NoSQL / Cache | Library | Import Path | Transformation | |---------|-------------|----------------| | **MongoDB** | `go.mongodb.org/mongo-driver/mongo` | `mongo.Connect()` → `whatapmongo.Connect()` | | **Aerospike** | `github.com/aerospike/aerospike-client-go` | Closure wrap with `whatapsql.Wrap()` | ### External Services | Library | Import Path | Description | |---------|-------------|-------------| | **Sarama (IBM)** | `github.com/IBM/sarama` | Kafka client | | **Sarama (Shopify)** | `github.com/Shopify/sarama` | Kafka client | | **gRPC** | `google.golang.org/grpc` | Auto Server/Client Interceptor injection | | **Kubernetes** | `k8s.io/client-go` | Auto `config.Wrap()` injection | ``` -------------------------------- ### Environment Variable for Configuration File Path Source: https://github.com/whatap/go-api-inst/blob/main/docs/config.md Use the `WHATAP_INST_CONFIG` environment variable to specify the path to the custom configuration file for instrumentation. ```bash WHATAP_INST_CONFIG=./config.yaml ``` -------------------------------- ### github.com/gorilla/mux Instrumentation Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/web-frameworks.md Instructions for instrumenting the Gorilla Mux router using Whatap's wrapping function. ```APIDOC ## GET /health ### Description Checks the health status of the application. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The health status of the application (e.g., "ok", "degraded"). #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### Instrument database/sql Source: https://context7.com/whatap/go-api-inst/llms.txt Replaces standard sql.Open with the WhaTap-instrumented version to track database operations. ```go // Before db, err := sql.Open("mysql", "user:pass@/dbname") // After db, err := whatapsql.Open("mysql", "user:pass@/dbname") // All DB operations (Query, Exec, Prepare, Begin, etc.) are automatically tracked rows, err := db.Query("SELECT * FROM users WHERE id = ?", id) result, err := db.Exec("INSERT INTO users (name) VALUES (?)", name) ``` -------------------------------- ### Database Restoration Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/remove.md Restores database connection initializations for various SQL drivers and ORMs. ```go // Before (instrumented) db, err := whatapsql.Open("mysql", dsn) db, err := whatapsqlx.Open("mysql", dsn) db, err := whatapsqlx.Connect("mysql", dsn) db, err := whatapgorm.Open("mysql", dsn) // After (removed) db, err := sql.Open("mysql", dsn) db, err := sqlx.Open("mysql", dsn) db, err := sqlx.Connect("mysql", dsn) db, err := gorm.Open("mysql", dsn) ``` -------------------------------- ### Instrument http.Get with context.Context Parameter Source: https://github.com/whatap/go-api-inst/blob/main/docs/rules/web-frameworks.md Uses the provided context.Context parameter directly for http.Get calls, ensuring proper tracing. ```go // Before (context.Context parameter) func fetchData(ctx context.Context, url string) { resp, err := http.Get(url) } // After (uses ctx directly) func fetchData(ctx context.Context, url string) { resp, err := whataphttp.HttpGet(ctx, url) } ```