### NewProxy Example Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Example of how to create and run a new Proxy instance with provided configuration. Ensure the runner package is imported. ```go package main import ( "github.com/air-verse/air/runner" ) func main() { cfg := &runner.CfgProxy{ Enabled: true, ProxyPort: 8090, AppPort: 8080, AppStartTimeout: 5000, } proxy := runner.NewProxy(cfg) go proxy.Run() // Later: proxy.Reload() or proxy.Stop() } ``` -------------------------------- ### Install Air via Go Get -tool Source: https://github.com/air-verse/air/blob/master/README.md Install Air as a project tool using 'go get -tool'. Requires Go 1.25 or higher. After installation, it can be invoked using 'go tool air'. ```shell go get -tool github.com/air-verse/air@latest # then use it like so: go tool air -v ``` -------------------------------- ### Install Air via goblin.run Source: https://github.com/air-verse/air/blob/master/README.md Install Air using the goblin.run service. The binary is typically placed in /usr/local/bin/air, or a custom path can be specified using the PREFIX environment variable. ```shell # binary will be /usr/local/bin/air curl -sSfL https://goblin.run/github.com/air-verse/air | sh # to put to a custom path curl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh ``` -------------------------------- ### Proxy.Run Examples Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Demonstrates two ways to run the proxy: non-blocking using a goroutine, or blocking until shutdown. ```go proxy := runner.NewProxy(cfg) go proxy.Run() // Non-blocking with goroutine ``` ```go // Or blocking: proxy.Run() // Blocks until shutdown ``` -------------------------------- ### Complete Example Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md A comprehensive TOML configuration file demonstrating all available settings for Air. ```toml #:schema https://json.schemastore.org/any.json # Project root root = "." tmp_dir = "tmp" testdata_dir = "testdata" # Environment files to load env_files = [".env.development", ".env"] [build] # Pre-build commands pre_cmd = ["echo 'Starting build...'" ] # Build command cmd = "go build -o ./tmp/main ." # Post-exit commands post_cmd = ["echo 'Cleaning up...'" ] # Binary path and arguments entrypoint = ["./tmp/main"] args_bin = ["server", "--port", "8080"] # File watching configuration include_ext = ["go", "tpl", "tmpl", "html", "css"] exclude_dir = ["assets", "tmp", "vendor", "node_modules", "testdata"] exclude_regex = ["_test\\.go"] exclude_unchanged = true # Build behavior delay = 1000 # 1 second delay before rebuild stop_on_error = true send_interrupt = false kill_delay = 500 # File watching method poll = false poll_interval = 500 [log] time = false main_only = false silent = false [color] main = "magenta" watcher = "cyan" build = "yellow" runner = "green" mode = "auto" [misc] clean_on_exit = true startup_banner = "" [screen] clear_on_rebuild = true keep_scroll = true [proxy] enabled = true proxy_port = 8090 app_port = 8080 app_start_timeout = 5000 # Windows-specific overrides [build.windows] cmd = "go build -o ./tmp/main.exe ." entrypoint = ["tmp\\main.exe"] ``` -------------------------------- ### Install Air Development Dependencies Source: https://github.com/air-verse/air/blob/master/README.md Clone the Air project, install its dependencies using 'make ci', and then install the tool locally with 'make install'. This setup is for contributing to Air development. ```shell # Fork this project # Clone it mkdir -p $GOPATH/src/github.com/cosmtrek cd $GOPATH/src/github.com/cosmtrek git clone git@github.com:/air.git # Install dependencies cd air make ci # Explore it and happy hacking! make install ``` -------------------------------- ### Example Docker/Podman Run Source: https://github.com/air-verse/air/blob/master/README.md An example of running Air in a Docker container, specifying the working directory, volume mounts, and port mapping. ```shell docker run -it --rm \ -w "/go/src/github.com/cosmtrek/hub" \ -v $(pwd):/go/src/github.com/cosmtrek/hub \ -p 9090:9090 \ cosmtrek/air ``` -------------------------------- ### Proxy.Stop Example Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Example demonstrating the use of the Stop method, typically with `defer` to ensure graceful shutdown when the proxy is no longer needed. ```go defer proxy.Stop() proxy.Run() ``` -------------------------------- ### Build Configuration Example Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Configures build commands, file watching, and execution behavior. Includes pre/post build commands, entrypoint, arguments, and file inclusion/exclusion rules. ```toml [build] pre_cmd = ["echo 'Building...' "] cmd = "go build -o ./tmp/main ." post_cmd = ["echo 'Build complete'"] entrypoint = ["./tmp/main"] args_bin = ["server", ":8080"] include_ext = ["go", "html", "css"] exclude_dir = ["vendor", "node_modules", "tmp"] delay = 1000 stop_on_error = true send_interrupt = false kill_delay = 500 ``` -------------------------------- ### Run Air Source: https://github.com/air-verse/air/blob/master/README.md The simplest way to start Air is by running the command in your project's root directory. ```shell air ``` -------------------------------- ### Install Air via Scoop Source: https://github.com/air-verse/air/blob/master/README.md Install Air using the Scoop package manager on Windows. ```shell scoop install air ``` -------------------------------- ### Install Air via Go Install Source: https://github.com/air-verse/air/blob/master/README.md Install the latest version of Air using the go install command. Requires Go 1.25 or higher. ```shell go install github.com/air-verse/air@latest ``` -------------------------------- ### Logger Setup Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Manages colored output for different components of the application. Supports various log levels and customizable colors. ```go type logger struct { config *Config colors map[string]string loggers map[string]logFunc } func (l *logger) main() logFunc func (l *logger) build() logFunc func (l *logger) runner() logFunc func (l *logger) watcher() logFunc // Supported Colors: red, green, yellow, blue, magenta, cyan, white ``` -------------------------------- ### Air Runner Quick Start Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md This Go code snippet demonstrates how to initialize Air's configuration, create and run the engine, and handle interrupt signals for graceful shutdown. ```APIDOC ## Quick Start This Go code snippet demonstrates how to initialize Air's configuration, create and run the engine, and handle interrupt signals for graceful shutdown. ```go package main import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" ) func main() { // Load configuration from .air.toml (or use defaults) cfg, _ := runner.InitConfig(".air.toml", nil) // Create and start the engine engine, _ := runner.NewEngineWithConfig(cfg, false) // Handle interrupt signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() // Run (blocks until Stop() is called) engine.Run() } ``` ``` -------------------------------- ### Root-Level Configuration Example Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Defines the working directory, temporary directory, test data directory, and environment files to load. ```toml root = "." tmp_dir = "tmp" testdata_dir = "testdata" env_files = [".env.development", ".env"] ``` -------------------------------- ### Install Air via mise Source: https://github.com/air-verse/air/blob/master/README.md Install and manage Air using the mise version manager. ```shell mise use -g air ``` -------------------------------- ### Docker Compose configuration for Air Source: https://github.com/air-verse/air/blob/master/README.md Example Docker Compose setup to run a project with Air, including volume mounts and environment variables. ```yaml services: my-project-with-air: image: cosmtrek/air # working_dir value has to be the same of mapped volume working_dir: /project-package ports: - : environment: - ENV_A=${ENV_A} - ENV_B=${ENV_B} - ENV_C=${ENV_C} volumes: - ./project-relative-path/:/project-package/ ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md Provides a basic TOML configuration for Air, specifying the root directory and temporary directory. ```APIDOC ## Minimal Configuration Example ### Description This is a minimal `.air.toml` configuration file that sets the project's root directory and the directory for temporary files. ### Configuration ```toml root = "." tmp_dir = "tmp" [build] cmd = "go build -o ./tmp/main ." entrypoint = ["./tmp/main"] ``` ``` -------------------------------- ### Example Usage with Air Proxy Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to configure and use Air with the proxy to enable live-reload for a Go application. ```bash # Start your Go app on port 8080 go run main.go # Runs on :8080 # Configure Air to proxy to port 8080 on proxy port 8090 air -c .air.toml # Access via proxy curl http://localhost:8090/ # Returns your app with live-reload script injected ``` -------------------------------- ### ProxyStream Usage Example Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Demonstrates the basic usage of ProxyStream, including adding a subscriber, triggering a reload, and removing the subscriber. ```go stream := runner.NewProxyStream() sub := stream.AddSubscriber() stream.Reload() stream.RemoveSubscriber(sub.id) ``` -------------------------------- ### Create and Run Engine Source: https://github.com/air-verse/air/blob/master/_autodocs/README.md Creates a new Air engine instance with the provided configuration and starts its execution. Assumes configuration is already loaded. ```go engine, err := runner.NewEngineWithConfig(cfg, false) engine.Run() ``` -------------------------------- ### Install Air via Homebrew Source: https://github.com/air-verse/air/blob/master/README.md Install Air using the Homebrew package manager on macOS or Linux. ```shell brew install go-air ``` -------------------------------- ### Install Air via install.sh Script Source: https://github.com/air-verse/air/blob/master/README.md Install Air using a shell script downloaded via curl. The binary can be placed in $(go env GOPATH)/bin/air or a specified local directory. ```shell # binary will be $(go env GOPATH)/bin/air curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin # or install it into ./bin/ curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh air -v ``` -------------------------------- ### Example Usage of ParseConfigFlag Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/flag.md This example demonstrates how to use ParseConfigFlag to generate flags, parse them, and initialize configuration. It's useful for setting up application configurations via command-line arguments. ```go package main import ( "flag" "github.com/air-verse/air/runner" ) func main() { flags := runner.ParseConfigFlag(flag.CommandLine) flag.Parse() // Now you can use the flags with InitConfig cfg, _ := runner.InitConfig(".air.toml", flags) } ``` -------------------------------- ### Proxy.BuildFailed Example Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Example of using the BuildFailed method to send detailed error information to connected clients. This prevents a full page reload by displaying errors directly in the browser. ```go msg := runner.BuildFailedMsg{ Error: "undefined: MyVar", Command: "go build -o ./tmp/main .", Output: "main.go:42: undefined: MyVar", } proxy.BuildFailed(msg) ``` -------------------------------- ### Add Go Bin to PATH Source: https://github.com/air-verse/air/blob/master/README.md Ensure the Go binary directory is included in your system's PATH environment variable to execute Air after installation with 'go install'. ```shell export PATH="$PATH:$(go env GOPATH)/bin" ``` -------------------------------- ### Proxy.Reload Example Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Example of calling the Reload method to trigger a page refresh in connected browsers. Typically called after a successful build. ```go // Called from build completion handler proxy.Reload() // Triggers reload in all connected browsers ``` -------------------------------- ### Docker Compose for local development with Air Source: https://github.com/air-verse/air/blob/master/README.md Example docker-compose.yaml to set up a local development environment with live reload using Air. ```yaml version: "3.8" services: web: build: context: . # Correct the path to your Dockerfile dockerfile: Dockerfile ports: - 8080:3000 # Important to bind/mount your codebase dir to /app dir for live reload volumes: - ./:/app ``` -------------------------------- ### Example Docker/Podman Run with Config and Port Source: https://github.com/air-verse/air/blob/master/README.md Demonstrates running Air in Docker, setting the AIR_PORT environment variable, and specifying a configuration file. The '$@' captures any additional arguments passed to the 'air' function. ```shell cd /go/src/github.com/cosmtrek/hub AIR_PORT=8080 air -c "config.toml" ``` -------------------------------- ### Log Configuration Example Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Configures logging output, including options for timestamps, main logs only, and silencing all logs. ```toml [log] time = false main_only = false silent = false ``` -------------------------------- ### Command-Line Overrides Example Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md Illustrates how to override TOML configuration values using command-line arguments when initializing the Air configuration. ```APIDOC ## Command-Line Overrides Example ### Description This example demonstrates how to override specific configuration settings defined in a `.air.toml` file directly when initializing the configuration using `runner.InitConfig`. ### Usage Pass a map of `runner.TomlInfo` to the `InitConfig` function to specify values for configuration keys like `build.cmd` or `proxy.enabled`. ```go cfg, err := runner.InitConfig(".air.toml", map[string]runner.TomlInfo{ "build.cmd": {Value: ptrTo("go build -o ./bin/app .")}, "proxy.enabled": {Value: ptrTo("true")}, }) engine, _ := runner.NewEngineWithConfig(cfg, false) engine.Run() ``` ``` -------------------------------- ### Run Engine and Enter Event Loop Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md The Run method starts the Engine, initializes watchers, and enters a blocking event loop. It monitors file changes, triggers builds, runs the binary, and handles live-reloading. This method blocks until Stop() is called. ```go func (e *Engine) Run() ``` ```go package main import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" "log" ) func main() { engine, err := runner.NewEngine(".air.toml", nil, false) if err != nil { log.Fatal(err) } // Handle interrupt signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() // This blocks until Stop() is called engine.Run() } ``` -------------------------------- ### Interrupt Handling Example Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md Demonstrates how to handle interrupt signals (SIGINT, SIGTERM) to gracefully stop the Air engine. ```APIDOC ## Interrupt Handling Example ### Description This example shows how to set up signal handling to catch interrupt signals (like Ctrl+C) and stop the Air engine gracefully. ### Usage Import necessary packages, initialize the configuration and engine, set up a signal channel, and run the engine in a goroutine that listens for signals to stop the engine. ```go import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" ) cfg, _ := runner.InitConfig(".air.toml", nil) engine, _ := runner.NewEngineWithConfig(cfg, false) sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() engine.Run() ``` ``` -------------------------------- ### Engine.Run Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md Starts the Engine, initializing watchers and entering the main event loop. This method blocks until the engine is stopped. ```APIDOC ## Engine.Run ### Description Starts the Engine, initializing watchers and entering the main event loop. This method blocks until the engine is stopped. The `Run` method performs initialization of the run environment, sets up file watchers for all configured directories, and enters an event loop that: 1. Monitors files for changes 2. Triggers builds when files change 3. Runs the built binary 4. Optionally proxies HTTP requests for live-reload functionality 5. Handles signals to gracefully stop ### Method func (e *Engine) Run() ### Parameters None ### Throws/Rejects - Calls `os.Exit(1)` if environment check fails - Calls `os.Exit(1)` if directory watching setup fails ### Example ```go package main import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" "log" ) func main() { engine, err := runner.NewEngine(".air.toml", nil, false) if err != nil { log.Fatal(err) } // Handle interrupt signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() // This blocks until Stop() is called engine.Run() } ``` ``` -------------------------------- ### Proxy.Run Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Starts the HTTP proxy server and blocks until it receives a shutdown signal. It registers handlers for proxying, SSE reload broadcasts, and worker script serving, then listens on the configured port. ```APIDOC ## Proxy.Run ### Description Starts the HTTP proxy server and blocks until it receives a shutdown signal. ### Method func (p *Proxy) Run() ### Example ```go proxy := runner.NewProxy(cfg) go proxy.Run() // Non-blocking with goroutine // Or blocking: proxy.Run() // Blocks until shutdown ``` ``` -------------------------------- ### Dockerfile for Air integration Source: https://github.com/air-verse/air/blob/master/README.md A Dockerfile to install Air globally within a Go environment, suitable for CI/CD or custom Docker images. ```Dockerfile # Choose whatever you want, version >= 1.25 FROM golang:1.25-alpine WORKDIR /app RUN go install github.com/air-verse/air@latest COPY go.mod go.sum ./ RUN go mod download CMD ["air", "-c", ".air.toml"] ``` -------------------------------- ### Get Default Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Returns the default configuration settings for the Air runner, which vary slightly based on the operating system. This is useful for initializing the runner with sensible defaults. ```go func defaultConfig() Config ``` -------------------------------- ### Define Proxy Configuration Structure Source: https://github.com/air-verse/air/blob/master/_autodocs/types.md HTTP proxy configuration used for browser live-reloading, including whether it's enabled, proxy port, application port, and application start timeout. ```go type cfgProxy struct { Enabled bool ProxyPort int AppPort int AppStartTimeout int } ``` -------------------------------- ### Build Entrypoint as String Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Specifies the binary to execute as a simple string. ```toml [build] entrypoint = "./tmp/main" ``` -------------------------------- ### Build Entrypoint with Default Arguments Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Specifies the binary to execute along with its default command-line arguments. ```toml [build] entrypoint = ["./tmp/main", "server", ":8080"] ``` -------------------------------- ### Initialize Air Engine and Run Application Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md This snippet demonstrates how to initialize Air's configuration, create an engine, and run the application, including handling interrupt signals for graceful shutdown. It loads configuration from a .air.toml file. ```go package main import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" ) func main() { // Load configuration from .air.toml (or use defaults) cfg, _ := runner.InitConfig(".air.toml", nil) // Create and start the engine engine, _ := runner.NewEngineWithConfig(cfg, false) // Handle interrupt signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() // Run (blocks until Stop() is called) engine.Run() } ``` -------------------------------- ### Initialize a New Project Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md This command initializes a new Air project by creating a `.air.toml` configuration file with sensible defaults. ```APIDOC ## Initialize a New Project This command initializes a new Air project by creating a `.air.toml` configuration file with sensible defaults. ```bash cd /path/to/project air init ``` ``` -------------------------------- ### Initialize and Run Air Engine Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md This snippet demonstrates how to load configuration from a file, create a new engine with that configuration, and then run the engine. The engine.Run() call blocks until the engine is stopped. ```go import "github.com/air-verse/air/runner" // Load config cfg, err := runner.InitConfig(".air.toml", nil) // Create and run engine engine, err := runner.NewEngineWithConfig(cfg, false) engine.Run() // Blocks until Stop() is called ``` -------------------------------- ### Initialize New Project with Air Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md Use this command to create a default .air.toml configuration file in your project directory. This file contains sensible defaults tailored for your operating system. ```bash cd /path/to/project air init ``` -------------------------------- ### isHiddenDirectory Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Checks if a path is a hidden directory (starts with "."). ```APIDOC ## isHiddenDirectory ### Description Checks if a path is a hidden directory (starts with "."). ### Method `func isHiddenDirectory(path string) bool` ### Example ```go isHiddenDirectory(".git") // true isHiddenDirectory("src") // false isHiddenDirectory("..") // false ``` ``` -------------------------------- ### Error Handling with InitConfig Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Demonstrates the common pattern of initializing configuration and checking for errors. Handles potential issues like missing configuration files or initialization failures. ```go cfg, err := InitConfig(".air.toml", nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Miscellaneous Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Configure miscellaneous options such as cleaning temporary directories on exit and setting a custom startup banner. ```toml [misc] clean_on_exit = false startup_banner = "My Custom Banner\n" ``` ```toml [misc] startup_banner = "" ``` -------------------------------- ### Build Entrypoint with PATH-Resolved Tools Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Configures the entrypoint to use a debugger like 'dlv', resolving it from the system's PATH. ```toml [build] entrypoint = [ "dlv", "exec", "--accept-multiclient", "--log", "--headless", "--continue", "--listen=:8999", "--api-version", "2", "./tmp/main" ] ``` -------------------------------- ### Create Engine from Config File Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md Use NewEngine to create an Engine instance by loading configuration from a specified file path. Command-line arguments can override file settings. The cfgPath can be an empty string to use default configurations. ```go func NewEngine(cfgPath string, args map[string]TomlInfo, debugMode bool) (*Engine, error) ``` ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { engine, err := runner.NewEngine(".air.toml", nil, false) if err != nil { log.Fatal(err) } defer engine.Stop() engine.Run() } ``` -------------------------------- ### Miscellaneous Configuration Options Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Sets miscellaneous options such as cleaning the temporary directory on exit and specifying a custom startup banner. Use this for general Air behavior adjustments. ```go type CfgMisc struct { CleanOnExit bool // Delete tmp directory when Air exits StartupBanner *string // Custom startup banner text (nil = default, "" = hide) } ``` -------------------------------- ### Initialize Air Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Creates a default configuration file for Air. This is the first step to customize Air's behavior. ```bash air init ``` -------------------------------- ### Create Engine with Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md Use NewEngineWithConfig to create an Engine instance with explicit configuration parameters and debug mode. Ensure the Config struct is properly populated with build, log, and proxy settings. ```go func NewEngineWithConfig(cfg *Config, debugMode bool) (*Engine, error) ``` ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { cfg := runner.Config{ Root: ".", TmpDir: "tmp", Build: runner.cfgBuild{ Cmd: "go build -o ./tmp/main .", Entrypoint: []string{"./tmp/main"}, }, } engine, err := runner.NewEngineWithConfig(&cfg, false) if err != nil { log.Fatal(err) } defer engine.Stop() engine.Run() } ``` -------------------------------- ### Configure Air startup banner Source: https://github.com/air-verse/air/blob/master/README.md Control the startup banner using the 'misc.startup_banner' TOML setting. An empty string suppresses the banner. ```toml [misc] # Not set (default): show built-in ASCII banner with version. # Set to empty string: print nothing. startup_banner = "" # Set to custom text: print this text instead of the built-in banner. # startup_banner = "API watcher" ``` -------------------------------- ### Get Terminal Color Attribute Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Maps color names to terminal color attributes. Used internally by the logger to apply colors to output. ```go func getColor(name string) color.Attribute c := getColor("magenta") // Returns: color.FgMagenta ``` -------------------------------- ### Initialize Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/README.md Loads the Air configuration from a specified TOML file. Handles potential errors during initialization. ```go cfg, err := runner.InitConfig(".air.toml", nil) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/air-verse/air/blob/master/README.md Before running Air, change the current directory to your Go project's root. ```shell cd /path/to/your_project ``` -------------------------------- ### Check if Directory is Hidden Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Identifies if a directory is considered hidden, typically by checking if its name starts with a dot ('.'). This is useful for filtering out configuration or version control directories. ```go isHiddenDirectory(".git") // true isHiddenDirectory("src") // false isHiddenDirectory("..") // false ``` -------------------------------- ### Initialize Air Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Loads and initializes the Air configuration from a file path with full preprocessing, including merging platform-specific overrides and command-line arguments. Use this for standard configuration loading. ```go func InitConfig(path string, cmdArgs map[string]TomlInfo) (*Config, error) ``` ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { cfg, err := runner.InitConfig(".air.toml", nil) if err != nil { log.Fatal(err) } // cfg is now fully initialized and ready to use engine, _ := runner.NewEngineWithConfig(cfg, false) engine.Run() } ``` -------------------------------- ### Handle Interrupts with Engine Stop Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md This Go snippet shows how to gracefully stop the Air engine when an interrupt signal (SIGINT or SIGTERM) is received. It initializes the config and engine, sets up signal notification, and starts a goroutine to listen for signals and stop the engine. ```go import ( "os" "os/signal" "syscall" "github.com/air-verse/air/runner" ) cfg, _ := runner.InitConfig(".air.toml", nil) engine, _ := runner.NewEngineWithConfig(cfg, false) sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs engine.Stop() }() engine.Run() ``` -------------------------------- ### Use Different Build Commands Per Platform Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md Define platform-specific build commands and entrypoints. This allows tailoring the build process for different operating systems. ```toml [build] cmd = "go build -o ./tmp/main ." entrypoint = ["./tmp/main"] [build.windows] cmd = "go build -o ./tmp/main.exe ." entrypoint = ["tmp\main.exe"] ``` -------------------------------- ### Platform-Specific Build Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md Demonstrates how to define platform-specific build commands and entrypoints in the Air configuration. ```APIDOC ## Platform-Specific Build Configuration ### Description This configuration example shows how to specify different build commands and entrypoints for Windows, overriding the default settings. ### Configuration ```toml [build] cmd = "go build -o ./tmp/main ." entrypoint = ["./tmp/main"] [build.windows] cmd = "go build -o ./tmp/main.exe ." entrypoint = ["tmp\main.exe"] ``` ``` -------------------------------- ### InitConfig Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Loads and initializes the configuration from a file path with full preprocessing. This function reads the config file, merges platform-specific overrides, applies command-line arguments, expands paths, validates settings, compiles exclude regex patterns, and resolves the entry point binary path. ```APIDOC ## InitConfig ### Description Loads and initializes the configuration from a file path with full preprocessing. ### Method `func InitConfig(path string, cmdArgs map[string]TomlInfo) (*Config, error)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to .air.toml config file; empty string uses default search paths #### Query Parameters - **cmdArgs** (map[string]TomlInfo) - Optional - Command-line argument overrides in format map[fieldPath]TomlInfo ### Response #### Success Response (*Config, error) Returns a fully initialized Config or an error. #### Error Handling - Returns error if the configuration file cannot be read - Returns error if TOML parsing fails - Returns error if path expansion fails - Returns error if regex compilation fails for exclude_regex patterns ### Request Example ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { cfg, err := runner.InitConfig(".air.toml", nil) if err != nil { log.Fatal(err) } engine, _ := runner.NewEngineWithConfig(cfg, false) engine.Run() } ``` ``` -------------------------------- ### NewProxy Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Creates a new Proxy instance with the given configuration. It initializes an HTTP server, an HTTP client, and the SSE stream, along with necessary handlers for routing and live-reload. ```APIDOC ## NewProxy ### Description Creates a new Proxy instance with the given configuration. ### Method func NewProxy(cfg *cfgProxy) *Proxy ### Parameters #### Path Parameters * cfg (*cfgProxy) - Required - Proxy configuration with port, app URL, and timeout settings ### Return Type *Proxy - A new Proxy instance ready to run. ### Example ```go package main import ( "github.com/air-verse/air/runner" ) func main() { cfg := &runner.CfgProxy{ Enabled: true, ProxyPort: 8090, AppPort: 8080, AppStartTimeout: 5000, } proxy := runner.NewProxy(cfg) go proxy.Run() // Later: proxy.Reload() or proxy.Stop() } ``` ``` -------------------------------- ### Apply Platform Defaults Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Adjusts default configuration settings based on the current operating system. Provides OS-specific build paths and command templates. ```go func applyPlatformDefaults(cfg *Config, goos string) // Changes for Windows: // - Build.Bin: `tmp\main.exe` // - Build.Cmd: `go build -o ./tmp/main.exe .` ``` -------------------------------- ### Apply Platform Overrides Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Applies platform-specific configuration overrides from sections like [build.windows], [build.darwin], or [build.linux]. ```go func applyPlatformOverrides(cfg *Config) error ``` -------------------------------- ### Override Configuration with Command-Line Arguments Source: https://github.com/air-verse/air/blob/master/_autodocs/INDEX.md This Go snippet demonstrates how to override settings from the .air.toml file using command-line arguments. It initializes the configuration with specific build and proxy settings provided as a map. ```go cfg, err := runner.InitConfig(".air.toml", map[string]runner.TomlInfo{ "build.cmd": {Value: ptrTo("go build -o ./bin/app .")}, "proxy.enabled": {Value: ptrTo("true")}, }) engine, _ := runner.NewEngineWithConfig(cfg, false) engine.Run() ``` -------------------------------- ### Define Miscellaneous Configuration Structure Source: https://github.com/air-verse/air/blob/master/_autodocs/types.md Miscellaneous configuration options, including whether to clean on exit and a pointer to a startup banner string. ```go type cfgMisc struct { CleanOnExit bool StartupBanner *string } ``` -------------------------------- ### Set Multiple Options Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/flag.md Configure various Air settings simultaneously, including build, log, and color options. ```bash air \ --build.cmd "make build" \ --build.entrypoint "./bin/app" \ --build.delay 2000 \ --log.time true \ --color.mode always ``` -------------------------------- ### Configure environment files for loading variables Source: https://github.com/air-verse/air/blob/master/README.md Specify environment files to load variables from before building and running. Later files overwrite earlier ones. ```toml # Loads .env.development and then .env files. # Values in the lattermost file overwrite any preceding ones. # Does not overwrite variables that were present before running air. env_files = [".env.development", ".env"] ``` -------------------------------- ### Load Environment Files Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md Specify a list of environment files to load. Air will load these files in the order provided. ```toml env_files = [".env.development", ".env"] ``` -------------------------------- ### List All Available Flags Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/flag.md Display all available command-line flags and their descriptions. ```bash air --help ``` -------------------------------- ### Override Build Command and Entrypoint via CLI Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Demonstrates overriding the build command and entrypoint using command-line flags. ```bash air --build.cmd "go build -o ./bin/api ." --build.entrypoint "./bin/api" ``` -------------------------------- ### Define Common Build Settings Structure Source: https://github.com/air-verse/air/blob/master/_autodocs/types.md Common build settings that are shared between base and platform-specific configurations, including pre/post commands, command to execute, binary path, and entrypoint. ```go type CfgBuildCommon struct { PreCmd []string Cmd string PostCmd []string Bin string Entrypoint []string FullBin string ArgsBin []string } ``` -------------------------------- ### defaultConfig Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Returns the default configuration for the current operating system. Includes default settings for root, temporary directory, build commands, included/excluded file extensions/directories, build delay, and log colors. Windows adjusts build settings to use `.exe`. ```APIDOC ## defaultConfig ### Description Returns the default configuration for the current operating system. ### Method `func defaultConfig() Config` ### Return Type `Config` — Default configuration. ### Defaults: - Root: "." - TmpDir: "tmp" - Build.Cmd: "go build -o ./tmp/main ." - Build.IncludeExt: ["go", "tpl", "tmpl", "html"] - Build.ExcludeDir: ["assets", "tmp", "vendor", "testdata"] - Build.Delay: 1000ms - Log colors: magenta (main), cyan (watcher), yellow (build), green (runner) Windows adjusts `Build.Bin` and `Build.Cmd` to use `.exe`. ``` -------------------------------- ### NewEngineWithConfig Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md Creates a new Engine instance with the given configuration and debug mode. It initializes the core components required for file watching, building, and running the application. ```APIDOC ## NewEngineWithConfig ### Description Creates a new Engine instance with the given configuration and debug mode. ### Method func ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | cfg | *Config | Yes | — | Configuration object specifying build, log, and proxy settings | | debugMode | bool | No | false | Enables debug logging output | ### Return Type `(*Engine, error)` — A new Engine instance or an error if initialization fails. ### Throws/Rejects - Returns error if the file watcher fails to initialize - Returns error if logger initialization fails ### Example ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { cfg := runner.Config{ Root: ".", TmpDir: "tmp", Build: runner.cfgBuild{ Cmd: "go build -o ./tmp/main .", Entrypoint: []string{"./tmp/main"}, }, } engine, err := runner.NewEngineWithConfig(&cfg, false) if err != nil { log.Fatal(err) } defer engine.Stop() engine.Run() } ``` ``` -------------------------------- ### Enable Proxy Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/flag.md Enable and configure the proxy feature with specified ports. ```bash air --proxy.enabled true --proxy.proxy_port 8090 --proxy.app_port 8080 ``` -------------------------------- ### Proxy Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Configure HTTP proxy settings for live-reload in browsers, including enabling the proxy, ports, and timeouts. ```toml [proxy] enabled = true proxy_port = 8090 app_port = 8080 app_start_timeout = 5000 ``` -------------------------------- ### Override Multiple Configuration Options via CLI Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Shows how to override multiple configuration settings like build delay, log time, and color mode using command-line flags. ```bash air --build.delay 2000 --log.time true --color.mode always ``` -------------------------------- ### Define Build Configuration Structure Source: https://github.com/air-verse/air/blob/master/_autodocs/types.md Configuration for the build process, including commands, watchers, binary paths, file inclusion/exclusion rules, and platform-specific overrides. It embeds common build settings. ```go type cfgBuild struct { CfgBuildCommon Log string IncludeExt []string ExcludeDir []string IncludeDir []string ExcludeFile []string IncludeFile []string ExcludeRegex []string ExcludeUnchanged bool IgnoreDangerousRootDir bool FollowSymlink bool Poll bool PollInterval int Delay int StopOnError bool SendInterrupt bool KillDelay time.Duration Rerun bool RerunDelay int Windows *cfgBuildOverrides Darwin *cfgBuildOverrides Linux *cfgBuildOverrides } ``` -------------------------------- ### Troubleshoot 'command not found: air' Source: https://github.com/air-verse/air/blob/master/README.md Ensure Air's binary path is correctly added to your system's PATH environment variable. ```shell export GOPATH=$HOME/xxxxx export PATH=$PATH:$GOROOT/bin:$GOPATH/bin export PATH=$PATH:$(go env GOPATH)/bin #Confirm this line in your .profile and make sure to source the .profile if you add it!!! ``` -------------------------------- ### Engine Logging Methods Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Provides methods for logging at different levels (main, build, watcher, runner) and for debugging. These methods respect log settings like silent and main_only. ```go func (e *Engine) mainLog(format string, v ...interface{}) func (e *Engine) buildLog(format string, v ...interface{}) func (e *Engine) watcherLog(format string, v ...interface{}) func (e *Engine) runnerLog(format string, v ...interface{}) func (e *Engine) mainDebug(format string, v ...interface{}) func (e *Engine) watcherDebug(format string, v ...interface{}) ``` -------------------------------- ### Run Air with a specific config file Source: https://github.com/air-verse/air/blob/master/README.md Use the -c flag to explicitly specify a configuration file for Air. ```shell air -c .air.toml ``` -------------------------------- ### Build Configuration Structure Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Defines the configuration for the build process, including commands, file watching, and platform-specific overrides. Use this to customize how Air builds your project. ```go type CfgBuild struct { CfgBuildCommon Log string // Log file name (placed in tmp_dir) IncludeExt []string // File extensions to watch (e.g., ["go", "html"]) ExcludeDir []string // Directories to ignore IncludeDir []string // Specific directories to watch ExcludeFile []string // File patterns to exclude IncludeFile []string // Specific files to watch ExcludeRegex []string // Regex patterns for exclusion ExcludeUnchanged bool // Skip rebuild if file content unchanged IgnoreDangerousRootDir bool // Ignore dangerous root directory warning FollowSymlink bool // Follow symbolic links Poll bool // Use polling instead of fsnotify PollInterval int // Poll interval in milliseconds (min 500ms) Delay int // Delay before triggering build (milliseconds) StopOnError bool // Stop running binary on build errors SendInterrupt bool // Send SIGINT before killing (Unix only) KillDelay time.Duration // Delay after SIGINT before SIGKILL Rerun bool // Whether to rerun the binary RerunDelay int // Delay between reruns (milliseconds) // Platform-specific overrides Windows *CfgBuildOverrides Darwin *CfgBuildOverrides Linux *CfgBuildOverrides } ``` -------------------------------- ### NewEngine Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/engine.md Creates a new Engine instance by reading configuration from a file path. This method allows for overriding configuration settings with command-line arguments. ```APIDOC ## NewEngine ### Description Creates a new Engine instance by reading configuration from a file path. ### Method func ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | cfgPath | string | Yes | — | Path to the .air.toml configuration file (empty string uses defaults) | | args | map[string]TomlInfo | No | nil | Command-line arguments that override config file settings | | debugMode | bool | No | false | Enables debug logging output | ### Return Type `(*Engine, error)` — A new Engine instance or an error if configuration loading fails. ### Throws/Rejects - Returns error if the configuration file cannot be read or parsed - Returns error if file watcher initialization fails ### Example ```go package main import ( "github.com/air-verse/air/runner" "log" ) func main() { engine, err := runner.NewEngine(".air.toml", nil, false) if err != nil { log.Fatal(err) } defer engine.Stop() engine.Run() } ``` ``` -------------------------------- ### Set Working Directory via Environment Variable Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Shows how to set the working directory for Air using the `air_wd` environment variable. ```bash export air_wd=/path/to/project air -c /custom/path/.air.toml ``` -------------------------------- ### Specify Directories to Watch Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Use `include_dir` to explicitly define which directories Air should watch. When `include_dir` is set, `exclude_dir` is ignored. ```toml [build] include_dir = ["cmd", "internal"] # Only watch these exclude_dir = [] # Will be ignored when include_dir is set ``` -------------------------------- ### Run with Custom Configuration Source: https://github.com/air-verse/air/blob/master/_autodocs/overview.md This command runs Air using a custom configuration file specified by the `-c` flag. ```APIDOC ## Run with Custom Configuration This command runs Air using a custom configuration file specified by the `-c` flag. ```bash air -c /path/to/custom.toml ``` ``` -------------------------------- ### Create File Watcher Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/utilities.md Creates a file watcher, either event-based (fsnotify) or polling, based on the configuration. The polling interval is clamped to a minimum of 500ms. ```go func newWatcher(cfg *Config) (filenotify.FileWatcher, error) ``` -------------------------------- ### Default Air Configuration (Windows) Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md These are the default settings Air uses on Windows if no configuration file is found. Note the differences in build command and entrypoint paths. ```go Build.Cmd: "go build -o ./tmp/main.exe ." Build.Entrypoint: ["tmp\\main.exe"] ``` -------------------------------- ### Common Build Configuration Fields Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Contains common build configuration fields applicable to both base and platform-specific configurations. Use this for shared build settings like pre/post commands and binary paths. ```go type CfgBuildCommon struct { PreCmd []string // Commands to execute before each build Cmd string // Build command (e.g., "go build -o ./tmp/main .") PostCmd []string // Commands to execute after ^C (cleanup) Bin string // Binary path (deprecated; use Entrypoint instead) Entrypoint []string // Binary path plus optional default arguments FullBin string // Full command with environment variables ArgsBin []string // Arguments passed to the binary at runtime } ``` -------------------------------- ### InitConfigForDisplay Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/config.md Loads configuration without preprocessing side effects, intended for read-only operations like displaying version information. Unlike InitConfig, this function does not perform environment variable loading, path resolution, or command execution. ```APIDOC ## InitConfigForDisplay ### Description Loads configuration without preprocessing side effects (used for displaying version info). ### Method `func InitConfigForDisplay(path string, cmdArgs map[string]TomlInfo) (*Config, error)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to .air.toml config file; empty string uses defaults #### Query Parameters - **cmdArgs** (map[string]TomlInfo) - Optional - Command-line argument overrides ### Response #### Success Response (*Config, error) Returns a Config with minimal preprocessing. ### Request Example ```go cfg, _ := runner.InitConfigForDisplay(".air.toml", nil) // Use cfg for display purposes without side effects ``` ``` -------------------------------- ### NewProxyStream Function Source: https://github.com/air-verse/air/blob/master/_autodocs/api-reference/proxy.md Creates and returns a new instance of ProxyStream, initializing the stream manager. ```go func NewProxyStream() *ProxyStream ``` -------------------------------- ### Override List Values via CLI Source: https://github.com/air-verse/air/blob/master/_autodocs/configuration.md Illustrates how to provide comma-separated values for list-type configuration options on the command line. ```bash air --build.exclude_dir "vendor,tmp,node_modules" ```