### Add Server to Upstream and Dump Config Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/AGENTS.md This example demonstrates how to add a new server to an existing upstream block within an nginx configuration string and then print the modified configuration. It uses `parser.NewStringParser` for in-memory configuration manipulation. ```go p := parser.NewStringParser(`http{ upstream backend{} }`) conf, _ := p.Parse() up := conf.FindUpstreams()[0] up.AddServer(&config.UpstreamServer{Address: "127.0.0.1:443"}) fmt.Println(dumper.DumpConfig(conf, dumper.IndentedStyle)) ``` -------------------------------- ### Commit Message Example Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/CONTRIBUTING.md Follow this format for commit messages to ensure clarity and readability. ```text fixed bug in http context * fixed parsing locations * cleanup variable replacing * ... ``` -------------------------------- ### Commit Message Example Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/AGENTS.md Example of a clear and logical commit message structure for contributing to the Gonginx project. Follow this format for pull requests. ```git fix parser include handling * handle recursive includes * add regression test ``` -------------------------------- ### Parse Nginx Config and Get Server Listen Ports Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Parses an Nginx configuration file to extract all server listen ports. Ensure the file path is correct. ```go func parseConfigAndGetPorts(filePath string) ([]string, error) { p, err := parser.NewParser(filePath) if err != nil { return nil, fmt.Errorf("failed to create parser: %w", err) } conf, err := p.Parse() if err != nil { return nil, fmt.Errorf("failed to parse config: %w", err) } servers := conf.FindDirectives("server") ports := make([]string, 0) for _, server := range servers { listens := server.GetBlock().FindDirectives("listen") if len(listens) > 0 { listenPorts := listens[0].GetParameters() ports = append(ports, listenPorts...) } } return ports, nil } func main() { ports, err := parseConfigAndGetPorts("../../testdata/full_conf/nginx.conf") if err != nil { panic(err) } fmt.Println(ports) } ``` -------------------------------- ### IBlock Interface Definition Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Defines the interface for configuration blocks, including methods to get directives, code block, and parent. ```go type IBlock interface { GetDirectives() []IDirective FindDirectives(directiveName string) []IDirective GetCodeBlock() string SetParent(IDirective) GetParent() IDirective } ``` -------------------------------- ### IDirective Interface Definition Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Defines the interface for configuration directives, including methods to get name, parameters, block, comment, and parent. ```go type IDirective interface { GetName() string //the directive name. GetParameters() []string GetBlock() IBlock GetComment() []string SetComment(comment []string) SetParent(IDirective) GetParent() IDirective } ``` -------------------------------- ### Update Proxy Pass Directive Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Finds and modifies the value of a 'proxy_pass' directive within an Nginx configuration. This example targets a specific URL and replaces it. ```go func main() { p := parser.NewStringParser( ` user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://www.google.com/; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } }` ) c, err := p.Parse() if err != nil { panic(err) } directives := c.FindDirectives("proxy_pass") for _, directive := range directives { fmt.Println("found a proxy_pass : ", directive.GetName(), directive.GetParameters()) if directive.GetParameters()[0] == "http://www.google.com/" { directive.GetParameters()[0] = "http://www.duckduckgo.com/" } } fmt.Println(dumper.DumpBlock(c.Block, dumper.IndentedStyle)) } ``` -------------------------------- ### Create Nginx Parser with Custom Options Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Demonstrates creating a new Nginx parser with specific options to control parsing behavior, such as skipping comments or validating custom directives. ```go p, err := parser.NewParser("nginx.conf", WithSkipComments(), WithCustomDirectives("hello_world"), WithSkipValidBlocks("my_block")) ``` -------------------------------- ### Import Gonginx Packages Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/AGENTS.md Import the necessary Gonginx packages for parsing, configuration modeling, and dumping nginx configuration files. Ensure Go modules are set up correctly. ```go import ( "github.com/tufanbarisyildirim/gonginx/config" "github.com/tufanbarisyildirim/gonginx/dumper" "github.com/tufanbarisyildirim/gonginx/parser" ) ``` -------------------------------- ### Parser Initialization Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Initializes a new parser for Nginx configuration files. ```APIDOC ## Parser Initialization ### Description Initializes a new parser for Nginx configuration files, with options to customize parsing behavior. ### Constructors #### `NewParser(filePath string, opts ...Option) (*Parser, error)` - `filePath` (string): The path to the Nginx configuration file. - `opts` ([]Option): A variadic list of options to configure the parser. #### `NewStringParser(content string, opts ...Option) (*Parser, error)` - `content` (string): The Nginx configuration content as a string. - `opts` ([]Option): A variadic list of options to configure the parser. #### `NewParserFromLexer(lexer *lexer, opts ...Option) *Parser` - `lexer` (*lexer): An existing lexer instance. - `opts` ([]Option): A variadic list of options to configure the parser. ### Options - `WithSkipIncludeParsingErr()`: Skips errors during include file parsing. - `WithDefaultOptions()`: Applies default parser options. - `WithSkipComments()`: Ignores comments during parsing. - `WithIncludeParsing()`: Enables parsing of include directives. - `WithIncludeCycleErr()`: Returns an error if an include cycle is detected. - `WithCustomDirectives(directives ...string)`: Parses specified custom directives without validation. - `WithSkipValidBlocks(blocks ...string)`: Skips validation for directives within specified blocks. - `WithSkipValidDirectivesErr()`: Skips errors for invalid directives. ### Example Usage ```go p, err := parser.NewParser("nginx.conf", WithSkipComments(), WithCustomDirectives("hello_world"), WithSkipValidBlocks("my_block")) ``` ``` -------------------------------- ### DumpConfig Function Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Dumps the entire configuration to a string. ```go func DumpConfig(c *config.Config, style *Style) string ``` -------------------------------- ### Run Tests Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/CONTRIBUTING.md Execute all tests to ensure code formatting and functionality. This command should be run in the root of the repository. ```bash make test ``` -------------------------------- ### Parse Nginx Config and Print Listen Ports Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/AGENTS.md Use this snippet to parse an nginx configuration file and extract the listen ports from all server blocks. Ensure the 'nginx.conf' file exists in the specified path. ```go p, err := parser.NewParser("nginx.conf") if err != nil { log.Fatal(err) } conf, err := p.Parse() if err != nil { log.Fatal(err) } servers := conf.FindDirectives("server") for _, srv := range servers { for _, listen := range srv.GetBlock().FindDirectives("listen") { fmt.Println(listen.GetParameters()[0].GetValue()) } } ``` -------------------------------- ### WriteConfig Function Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Writes the configuration to a file, with an option to include included files. ```go func WriteConfig(c *config.Config, style *Style, writeInclude bool) error ``` -------------------------------- ### Style Struct Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Defines the styling configuration for dumping Nginx configurations. ```APIDOC ## Style Struct ### Description Defines the styling configuration for dumping Nginx configurations, allowing customization of output format. ### Fields - `SortDirectives bool`: Whether to sort directives. - `SpaceBeforeBlocks bool`: Whether to add space before blocks. - `StartIndent int`: The starting indentation level. - `Indent int`: The indentation increment. - `Debug bool`: Enables debug mode. - `DisableLuaFormatting bool`: Disables Lua code formatting. - `LuaFormatter LuaFormatterFunc`: Custom Lua formatter function. ### Methods - `WithLuaFormatting(enabled bool) *Style`: Returns a new Style with Lua formatting enabled or disabled. - `WithLuaFormatter(formatter LuaFormatterFunc) *Style`: Returns a new Style with a custom Lua formatter. ``` -------------------------------- ### Style WithLuaFormatting Method Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Enables or disables Lua formatting for the style. ```go func (s *Style) WithLuaFormatting(enabled bool) *Style ``` -------------------------------- ### Dump Nginx Config String to File with Indentation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Dumps a given Nginx configuration string to a file using indented style. This function first parses the string and then writes the formatted configuration. Ensure the provided fullConf string is valid Nginx syntax. ```go func dumpConfigToFile(fullConf string, filePath string) error { p := parser.NewStringParser(fullConf) conf, err := p.Parse() if err != nil { return fmt.Errorf("failed to parse config: %w", err) } dumpString := dumper.DumpConfig(conf, dumper.IndentedStyle) if err := os.WriteFile(filePath, []byte(dumpString), 0644); err != nil { return fmt.Errorf("failed to write config file: %w", err) } return nil } func dumpAndWriteConfigFile(fullConf string, filePath string) error { p := parser.NewStringParser(fullConf) conf, err := p.Parse() if err != nil { return fmt.Errorf("failed to parse config: %w", err) } // set config file path conf.FilePath = filePath err = dumper.WriteConfig(conf, dumper.IndentedStyle, false) if err != nil { panic(err) } return nil } func main() { fullConf := `user www www; worker_processes 5; error_log logs/error.log; pid logs/nginx.pid; worker_rlimit_nofile 8192; events { worker_connections 4096; } http { include mime.types; include proxy.conf; include fastcgi.conf; index index.html index.htm index.php; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] $status ' '"$request" $body_bytes_sent "$http_referer" ' ' "$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; sendfile on; tcp_nopush on; server_names_hash_bucket_size 128; server { listen 80; server_name domain1.com www.domain1.com; access_log logs/domain1.access.log main; root html; location ~ \.php$ { fastcgi_pass 127.0.0.1:1025; } } server { listen 80; server_name domain2.com www.domain2.com; access_log logs/domain2.access.log main; location ~ ^/(images|javascript|js|css|flash|media|static)/ { root /var/www/virtual/big.server.com/htdocs; expires 30d; } location / { proxy_pass http://127.0.0.1:8080; } } upstream big_server_com { server 127.0.0.3:8000 weight=5; server 127.0.0.3:8001 weight=5; server 192.168.0.1:8000; server 192.168.0.1:8001; } server { listen 80; server_name big.server.com; access_log logs/big.server.access.log main; location / { proxy_pass http://big_server_com; } } }` // dump config with indented style dumpConfigToFile(fullConf, "nginx-temp.conf") // dump config to file with indented style dumpAndWriteConfigFile(fullConf, "./nginx-temp2.conf") } ``` -------------------------------- ### HTTP Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents the HTTP block in Nginx configuration. ```go type HTTP struct { Servers []*Server Directives []IDirective Comment []string Parent IBlock } ``` -------------------------------- ### Nginx Configuration Grammar (Yacc) Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/README.md Defines the basic grammar rules for Nginx configuration files using Yacc syntax. This is useful for understanding the structure that the parser expects. ```yacc %token Keyword Variable BlockStart BlockEnd Semicolon Regex %% config : /* empty */ | config directives ; block : BlockStart directives BlockEnd ; directives : directives directive ; directive : Keyword [parameters] (semicolon|block) ; parameters : parameters keyword ; keyword : Keyword | Variable | Regex ; ``` -------------------------------- ### NoIndentSortedSpaceStyle Default Style Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md A default style configuration with no indentation, sorted directives, and space before blocks. ```go NoIndentSortedSpaceStyle = &Style{ SortDirectives: true, SpaceBeforeBlocks: true, StartIndent: 0, Indent: 0, Debug: false, } ``` -------------------------------- ### NoIndentSortedStyle Default Style Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md A default style configuration with no indentation and sorted directives. ```go NoIndentSortedStyle = &Style{ SortDirectives: true, StartIndent: 0, Indent: 0, Debug: false, } ``` -------------------------------- ### Block Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Concrete implementation of the IBlock interface. ```go type Block struct { Directives []IDirective IsLuaBlock bool LiteralCode string Parent IBlock } ``` -------------------------------- ### Default Styles Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Predefined style configurations for common use cases. ```APIDOC ## Default Styles ### Description Predefined style configurations for common use cases. ### Styles - `NoIndentStyle`: Style with no indentation. - `IndentStyle`: Style with default indentation (4 spaces). - `NoIndentSortedStyle`: Style with no indentation and sorted directives. - `NoIndentSortedSpaceStyle`: Style with no indentation, sorted directives, and space before blocks. ``` -------------------------------- ### Style Struct Definition Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Defines styling options for dumping configurations, such as sorting and indentation. ```go type Style struct { SortDirectives bool SpaceBeforeBlocks bool StartIndent int Indent int Debug bool DisableLuaFormatting bool LuaFormatter LuaFormatterFunc } ``` -------------------------------- ### DumpBlock Function Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Converts an IBlock to its string representation. ```go func DumpBlock(b config.IBlock, style *Style) string ``` -------------------------------- ### Server Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents a server block within the HTTP block. ```go type Server struct { Block IBlock Comment []string Parent IBlock } ``` -------------------------------- ### NoIndentStyle Default Style Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md A default style configuration with no indentation and directives not sorted. ```go NoIndentStyle = &Style{ SortDirectives: false, StartIndent: 0, Indent: 0, Debug: false, } ``` -------------------------------- ### Config Directives Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Provides methods for interacting with directives within the parsed Nginx configuration. ```APIDOC ## Config Directives ### Description Methods for finding and retrieving directives from the parsed Nginx configuration object. ### Methods #### `FindDirectives(directiveName string) []IDirective` - Finds all directives with the specified name. - `directiveName` (string): The name of the directive to search for. - Returns a slice of `IDirective` interfaces. #### `FindUpstreams() []*Upstream` - Finds all upstream blocks in the configuration. - Returns a slice of `*Upstream` pointers. ``` -------------------------------- ### Parse Configuration Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Parses the Nginx configuration to generate a configuration object. ```APIDOC ## Parse Configuration ### Description Parses the Nginx configuration file or string content into a structured configuration object. ### Method `func (p *Parser) Parse() (*config.Config, error)` ### Returns - `*config.Config`: A pointer to the configuration object representing the parsed Nginx configuration. - `error`: An error if parsing fails. ``` -------------------------------- ### Directive Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Concrete implementation of the IDirective interface. ```go type Directive struct { Block IBlock Name string Parameters []string //TODO: Save parameters with their type Comment []string Parent IBlock } ``` -------------------------------- ### Run Race Detector Tests Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/CONTRIBUTING.md Run tests with the race detector enabled to find potential data races. This is recommended for parser/dumper safety changes. ```bash go test -race ./... ``` -------------------------------- ### Include Parsing Behavior Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/README.md Explains how Gonginx handles include directives. It deduplicates includes by canonical path and skips cyclic include branches by default. Use WithIncludeCycleErr to enable failing fast on cycles. ```go parser.WithIncludeParsing() parser.WithIncludeCycleErr() ``` -------------------------------- ### Add Server to Upstream Block Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Appends a new server configuration to an existing upstream block. Ensure the upstream block exists in the configuration. ```go func main() { p := parser.NewStringParser(`http{ upstream my_backend{ server 127.0.0.1:443; server 127.0.0.2:443 backup; } }`) conf, err := p.Parse() if err != nil { panic(err) } upstreams := conf.FindUpstreams() upstreams[0].AddServer(&config.UpstreamServer{ Address: "127.0.0.1:443", Parameters: map[string]string{ "weight": "5", }, Flags: []string{"down"}, }) fmt.Println(dumper.DumpBlock(conf.Block, dumper.IndentedStyle)) } ``` -------------------------------- ### Dumper Functions Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Functions for converting configuration structures into string representations. ```APIDOC ## Dumper Functions ### Description Functions for converting configuration structures into string representations. ### Functions - `DumpConfig(c *config.Config, style *Style) string`: Dumps the entire configuration. - `DumpBlock(b config.IBlock, style *Style) string`: Converts a block to a string. - `DumpDirective(d config.IDirective, style *Style) string`: Converts a directive to a string. - `DumpInclude(i *config.Include, style *Style) map[string]string`: Dumps the included AST. - `WriteConfig(c *config.Config, style *Style, writeInclude bool) error`: Writes the configuration to a file or output. ``` -------------------------------- ### Style WithLuaFormatter Method Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Sets a custom Lua formatter function for the style. ```go func (s *Style) WithLuaFormatter(formatter LuaFormatterFunc) *Style ``` -------------------------------- ### DumpInclude Function Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Stringifies an included AST. ```go func DumpInclude(i *config.Include, style *Style) map[string]string ``` -------------------------------- ### Update Server Listen Port in Nginx Config Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Updates the listen port for all server blocks in an Nginx configuration file. Requires the file path, old port, and new port as input. ```go func updateServerListenPort(filePath string, oldPort string, newPort string) (string, error) { p, err := parser.NewParser(filePath) if err != nil { return "", fmt.Errorf("failed to create parser: %w", err) } conf, err := p.Parse() if err != nil { return "", fmt.Errorf("failed to parse config: %w", err) } servers := conf.FindDirectives("server") for _, server := range servers { listens := server.GetBlock().FindDirectives("listen") for _, listen := range listens { if listen.GetParameters()[0] == oldPort { listenDirective := listen.(*config.Directive) listenDirective.Parameters[0] = newPort } } } changedConf := dumper.DumpConfig(conf, dumper.IndentedStyle) return changedConf, nil } func main() { filePath := "../../testdata/full_conf/nginx.conf" oldPort := "80" newPort := "8080" if changedConf, err := updateServerListenPort(filePath, oldPort, newPort); err != nil { log.Fatalf("Error updating server listen port: %v", err) } else { fmt.Println(changedConf) } } ``` -------------------------------- ### Query and Update Server Listen Port Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Retrieves listen ports and modifies the listen port for a specific server. Requires the server to be found by its server name. ```go func main() { p := parser.NewStringParser(`http{ server{ listen 80; server_name example.com www.example.com; location /api { proxy_pass http://127.0.0.1:5000; } } }`) conf, err := p.Parse() if err != nil { panic(err) } httpBlocks := conf.FindDirectives("http") http, ok := httpBlocks[0].(*config.HTTP) if !ok { panic("http directive type mismatch") } server := http.GetServerByServerName("example.com") if server == nil { panic("server not found") } ports := server.GetListenPorts() // []int{80} fmt.Println(ports) if err := server.SetListenPort(0, 8080); err != nil { panic(err) } locations := server.GetLocations() fmt.Println(len(locations)) } ``` -------------------------------- ### IndentedStyle Default Style Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md A default style configuration with 4-space indentation and directives not sorted. ```go IndentedStyle = &Style{ SortDirectives: false, StartIndent: 0, Indent: 4, Debug: false, } ``` -------------------------------- ### UpstreamServer Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents a server within an upstream block. ```go type UpstreamServer struct { Address string Flags []string Parameters map[string]string Comment []string Parent IBlock } ``` -------------------------------- ### Upstream Lookup Methods Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/README.md Details the methods for finding upstreams. FindUpstreams() is permissive and skips unexpected types, while FindUpstreamsStrict() returns a typed error for non-config.Upstream types. ```go FindUpstreams() FindUpstreamsStrict() ``` -------------------------------- ### DumpDirective Function Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Converts an IDirective to its string representation. ```go func DumpDirective(d config.IDirective, style *Style) string ``` -------------------------------- ### IDirective Interface Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents a single directive within an Nginx configuration. It provides methods to access and modify the directive's name, parameters, block, comment, and parent. ```APIDOC ## IDirective Interface ### Description Represents a single directive within an Nginx configuration. It provides methods to access and modify the directive's name, parameters, block, comment, and parent. ### Methods - `GetName() string`: Returns the directive's name. - `GetParameters() []string`: Returns the directive's parameters. - `GetBlock() IBlock`: Returns the block associated with the directive. - `GetComment() []string`: Returns the comment associated with the directive. - `SetComment(comment []string)`: Sets the comment for the directive. - `SetParent(IDirective)`: Sets the parent directive. - `GetParent() IDirective`: Returns the parent directive. ``` -------------------------------- ### IBlock Interface Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents a block of directives within an Nginx configuration. It provides methods to access directives, code blocks, and parent information. ```APIDOC ## IBlock Interface ### Description Represents a block of directives within an Nginx configuration. It provides methods to access directives, code blocks, and parent information. ### Methods - `GetDirectives() []IDirective`: Returns the list of directives within the block. - `FindDirectives(directiveName string) []IDirective`: Finds directives by name within the block. - `GetCodeBlock() string`: Returns the raw code block content. - `SetParent(IDirective)`: Sets the parent directive for the block. - `GetParent() IDirective`: Returns the parent directive of the block. ``` -------------------------------- ### Upstream Struct Implementation Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Represents an upstream block in Nginx configuration. ```go type Upstream struct { UpstreamName string UpstreamServers []*UpstreamServer //Directives Other directives in upstream (ip_hash; etc) Directives []IDirective Comment []string Parent IBlock } ``` -------------------------------- ### Add Location to Server Block Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Adds a new location block with a proxy_pass directive to an existing server block. Verifies that a server block is present. ```go func main() { p := parser.NewStringParser(`http{ server{ listen 80; } }`) conf, err := p.Parse() if err != nil { panic(err) } servers := conf.FindDirectives("server") if len(servers) == 0 { panic("no server block found") } server, ok := servers[0].(*config.Server) if !ok { panic("server directive type mismatch") } server.AddLocation(&config.Location{ Directive: &config.Directive{ Name: "location", Parameters: []config.Parameter{{Value: "/api"}}, Block: &config.Block{ Directives: []config.IDirective{ &config.Directive{ Name: "proxy_pass", Parameters: []config.Parameter{{Value: "http://127.0.0.1:5000"}}, }, }, }, }, Match: "/api", }) fmt.Println(dumper.DumpBlock(conf.Block, dumper.IndentedStyle)) } ``` -------------------------------- ### Add Custom Directive to Nginx Block Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md Adds a custom directive to the first occurrence of a specified block in an Nginx configuration string. Useful for dynamically modifying configurations. ```go func addCustomDirective(fullConf string, blockName string, directiveName string, directiveValue string) (string, error) { p := parser.NewStringParser(fullConf) conf, err := p.Parse() if err != nil { return "", fmt.Errorf("failed to parse config: %w", err) } blocks := conf.FindDirectives(blockName) if len(blocks) == 0 { return "", fmt.Errorf("no such block: %s", blockName) } block := blocks[0].GetBlock() newDirective := &config.Directive{ Name: directiveName, Parameters: []string{directiveValue}, } realBlock := block.(*config.Block) realBlock.Directives = append(realBlock.Directives, newDirective) return dumper.DumpConfig(conf, dumper.IndentedStyle), nil } func main() { fullConf := `http{ upstream my_backend{ server 127.0.0.1:443; server 127.0.0.2:443 backup; } server { listen 8080; location / { root /var/www/html; index index.html; } } server { listen 9090; location / { root /var/www/html; index index.html; } } }` blockName := "server" directiveName := "access_log" directiveValue := "/var/log/nginx/access.log" newFullConf, err := addCustomDirective(fullConf, blockName, directiveName, directiveValue) if err != nil { log.Fatalf("Error adding custom directive: %v", err) } fmt.Println("New Full Config:", newFullConf) } ``` -------------------------------- ### Update Server Listen Port Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md This function updates the listen port for all server blocks in an Nginx configuration file. ```APIDOC ## Update Server Listen Port ### Description Updates the listen port for all server blocks in an Nginx configuration file. ### Function Signature `func updateServerListenPort(filePath string, oldPort string, newPort string) (string, error)` ### Parameters - `filePath` (string): The path to the Nginx configuration file. - `oldPort` (string): The current listen port to be replaced. - `newPort` (string): The new listen port. ### Returns - `string`: The modified Nginx configuration as a string. - `error`: An error if the operation fails. ``` -------------------------------- ### Add Custom Directive Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/GUIDE.md This function adds a custom directive to a specified block within an Nginx configuration string. ```APIDOC ## Add Custom Directive ### Description Adds a custom directive to a specified block within an Nginx configuration string. ### Function Signature `func addCustomDirective(fullConf string, blockName string, directiveName string, directiveValue string) (string, error)` ### Parameters - `fullConf` (string): The complete Nginx configuration as a string. - `blockName` (string): The name of the block to which the directive will be added (e.g., "server", "http"). - `directiveName` (string): The name of the custom directive to add (e.g., "access_log"). - `directiveValue` (string): The value of the custom directive. ### Returns - `string`: The modified Nginx configuration with the added directive. - `error`: An error if the block is not found or parsing fails. ``` -------------------------------- ### Fuzz Parser Safety Source: https://github.com/tufanbarisyildirim/gonginx/blob/master/CONTRIBUTING.md Perform a focused fuzz run on the parser to check for panics. This is optional but recommended for parser/dumper safety changes. Adjust -fuzztime as needed. ```bash go test -run=^$ -fuzz=FuzzParserParseNoPanic -fuzztime=5s ./parser ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.