### Install go-powerdns Source: https://github.com/joeig/go-powerdns/blob/main/README.md Use `go get` to install the latest version of the go-powerdns library. ```shell go get -u github.com/joeig/go-powerdns/v3 ``` -------------------------------- ### Client Structure and Example Usage Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/client.md Overview of the services available through the Client struct and an example demonstrating common operations. ```APIDOC ## Client Structure The Client struct exposes the following services: - **Config**: Configuration settings management - **Cryptokeys**: DNSSEC cryptographic key management - **Metadata**: Zone metadata operations - **Records**: DNS resource record management - **Search**: Full-text search across zones and records - **Servers**: Server information and cache operations - **Statistics**: Server statistics and metrics - **Zones**: Zone management - **TSIGKeys**: TSIG key management ## Example Usage ```go package main import ( "context" "log" "github.com/joeig/go-powerdns/v3" ) func main() { client := powerdns.New("http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw")) ctx := context.Background() // List all zones zones, err := client.Zones.List(ctx) if err != nil { log.Fatal(err) } // Create a new zone newZone, err := client.Zones.AddNative( ctx, "example.com", false, // DNSSEC disabled "", // nsec3param false, // nsec3narrow "", // soa_edit "", // soa_edit_api false, // api_rectify []string{"ns1.example.com."} ) if err != nil { log.Fatal(err) } log.Printf("Created zone: %s\n", *newZone.Name) // Add a record err = client.Records.Add( ctx, "example.com", "www.example.com", powerdns.RRTypeA, 3600, []string{"192.0.2.1"}, ) if err != nil { log.Fatal(err) } log.Println("Record added successfully") } ``` ``` -------------------------------- ### Example Usage of Type Pointer Helpers Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/types.md Demonstrates how to use the String and Bool helper functions to create a Zone object with optional fields set. ```go zone := &Zone{ Name: String("example.com"), Kind: ZoneKindPtr(NativeZoneKind), DNSsec: Bool(true), } ``` -------------------------------- ### Full PowerDNS Client Example Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/client.md Demonstrates a complete workflow using the PowerDNS client, including listing zones, creating a new zone, and adding a DNS record. Requires API key and client initialization. ```go package main import ( "context" "log" "github.com/joeig/go-powerdns/v3" ) func main() { client := powerdns.New("http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw")) ctx := context.Background() // List all zones zones, err := client.Zones.List(ctx) if err != nil { log.Fatal(err) } // Create a new zone newZone, err := client.Zones.AddNative( ctx, "example.com", false, // DNSSEC disabled "", // nsec3param false, // nsec3narrow "", // soa_edit "", // soa_edit_api false, // api_rectify []string{"ns1.example.com."} ) if err != nil { log.Fatal(err) } log.Printf("Created zone: %s\n", *newZone.Name) // Add a record err = client.Records.Add( ctx, "example.com", "www.example.com", powerdns.RRTypeA, 3600, []string{"192.0.2.1"}, ) if err != nil { log.Fatal(err) } log.Println("Record added successfully") } ``` -------------------------------- ### Migrate from Deprecated NewClient to New Function Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md This example demonstrates the migration from the deprecated `NewClient` function to the recommended `New` function for initializing the PowerDNS client. The new function simplifies configuration by using options like `WithAPIKey`. ```go // Old (deprecated) client := powerdns.NewClient( "http://localhost:8001", "localhost", map[string]string{}, nil, ) // New (recommended) client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw"), ) ``` -------------------------------- ### Go Context Usage with PowerDNS Client Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Demonstrates how to use `context.Context` with the PowerDNS client for managing timeouts and cancellations. Includes examples for `context.WithTimeout`, `context.WithCancel`, and `context.Background`. ```go import ( "context" "time" ) // With timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() zone, err := client.Zones.Get(ctx, "example.com") // With cancellation ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Cancel from another goroutine if needed go func() { time.Sleep(5 * time.Second) cancel() }() zones, err := client.Zones.List(ctx) // Background context (no timeout/cancellation) ctx := context.Background() zones, err := client.Zones.List(ctx) ``` -------------------------------- ### Go - Search for Comments by Pattern Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/search.md This example shows how to search specifically for comments that contain a given pattern. It returns a maximum number of matching comment results. ```go // Search for comments comments, err := client.Search.Data(ctx, "*deprecated*", 100, powerdns.SearchObjectTypeComment) if err != nil { log.Fatal(err) } for _, comment := range comments { fmt.Printf("Comment in %s: %s\n", *comment.Zone, *comment.Content, ) } ``` -------------------------------- ### Go - Search Only for Records by Pattern Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/search.md This example demonstrates how to filter search results to include only records that match a specific pattern. It limits the number of returned records. ```go // Search only for records records, err := client.Search.Data(ctx, "*.example.com", 50, powerdns.SearchObjectTypeRecord) if err != nil { log.Fatal(err) } for _, record := range records { fmt.Printf("Record: %s (%s) -> %s\n", *record.Name, *record.Type, *record.Content, ) } ``` -------------------------------- ### List All Servers Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/servers.md Retrieves a list of all configured servers (virtual hosts). Use this to get an overview of your PowerDNS server setup. ```go servers, err := client.Servers.List(ctx) if err != nil { log.Fatal(err) } for _, server := range servers { fmt.Printf("Server ID: %s\n", *server.ID) fmt.Printf(" Type: %s\n", *server.Type) fmt.Printf(" Daemon Type: %s\n", *server.DaemonType) fmt.Printf(" Version: %s\n", *server.Version) fmt.Printf(" URL: %s\n", *server.URL) } ``` -------------------------------- ### Basic PowerDNS Client Configuration Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Minimal setup for the PowerDNS client using an API key. Ensure the PowerDNS API is accessible at the specified URL. ```go client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw"), ) ``` -------------------------------- ### List TSIG Keys Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md Retrieves all TSIG keys configured on the server. Use this to get an overview of existing keys. ```go tsigkeys, err := client.TSIGKeys.List(ctx) if err != nil { log.Fatal(err) } for _, key := range tsigkeys { fmt.Printf("Key: %s, Algorithm: %s\n", *key.Name, *key.Algorithm, ) } ``` -------------------------------- ### Get All Records for a Name Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/records.md Use the Get method with a nil recordType to retrieve all DNS resource record sets for a given domain and name. The results include type, TTL, and record content. ```go rrsets, err := client.Records.Get(ctx, "example.com", "www.example.com", nil) if err != nil { log.Fatal(err) } for _, rrset := range rrsets { fmt.Printf("Type: %s, TTL: %d\n", *rrset.Type, *rrset.TTL) for _, record := range rrset.Records { fmt.Printf(" Content: %s\n", *record.Content) } } ``` -------------------------------- ### Go - Search for Zones by Pattern Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/search.md Use this snippet to find zones whose names start with a specific pattern. It returns a maximum number of matching zone results. ```go // Search for zones starting with "test" zones, err := client.Search.Data(ctx, "test*", 100, powerdns.SearchObjectTypeZone) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Manage Zones Source: https://github.com/joeig/go-powerdns/blob/main/README.md Perform operations on zones, including listing, getting, exporting, adding, changing, and deleting zones. ```go zones, err := pdns.Zones.List(ctx) zone, err := pdns.Zones.Get(ctx, "example.com") export, err := pdns.Zones.Export(ctx, "example.com") zone, err := pdns.Zones.AddNative(ctx, "example.com", true, "", false, "foo", "foo", true, []string{"ns.foo.tld."}) err := pdns.Zones.Change(ctx, "example.com", &zone) err := pdns.Zones.Delete(ctx, "example.com") ``` -------------------------------- ### Rotate TSIG Keys Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md This example demonstrates a safe TSIG key rotation process. It involves creating a new key, updating the zone to accept both old and new keys, waiting for propagation, removing the old key from the zone configuration, and finally deleting the old key. ```go // 1. Create new key newKey, err := client.TSIGKeys.Create( ctx, "zone-transfer-key-new", "hmac-sha256", "", ) if err != nil { log.Fatal(err) } // 2. Update zone to use both old and new keys zone, err := client.Zones.Get(ctx, "example.com") if err != nil { log.Fatal(err) } newKeyID := *newKey.ID zone.SlaveTSIGKeyIDs = append(zone.SlaveTSIGKeyIDs, newKeyID) err = client.Zones.Change(ctx, "example.com", zone) if err != nil { log.Fatal(err) } fmt.Println("New key added to zone - zone now accepts both keys") // 3. Wait for replication/propagation... // 4. Remove old key from zone zone, err = client.Zones.Get(ctx, "example.com") if err != nil { log.Fatal(err) } // Remove old key ID from SlaveTSIGKeyIDs oldKeyID := "old-key-id" newSlaveTSIGKeyIDs := make([]string, 0) for _, id := range zone.SlaveTSIGKeyIDs { if id != oldKeyID { newSlaveTSIGKeyIDs = append(newSlaveTSIGKeyIDs, id) } } zone.SlaveTSIGKeyIDs = newSlaveTSIGKeyIDs err = client.Zones.Change(ctx, "example.com", zone) if err != nil { log.Fatal(err) } fmt.Println("Old key removed from zone") // 5. Delete old key after propagation // err = client.TSIGKeys.Delete(ctx, oldKeyName) ``` -------------------------------- ### Retrieve All Server Configuration Settings Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/config.md Use this method to get a list of all current configuration settings applied to the PowerDNS server. It requires a context for request management. ```go func (c *ConfigService) List(ctx context.Context) ([]ConfigSetting, error) ``` ```go config, err := client.Config.List(ctx) if err != nil { log.Fatal(err) } for _, setting := range config { fmt.Printf("Setting: %s\n", *setting.Name) fmt.Printf(" Type: %s\n", *setting.Type) fmt.Printf(" Value: %s\n", *setting.Value) } ``` -------------------------------- ### Health Check with Server Information Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/servers.md Uses the `Get` method to retrieve server information as a basic health check. Verifies server reachability and that essential fields like 'Version' are populated. ```go server, err := client.Servers.Get(ctx, "localhost") if err != nil { fmt.Println("ERROR: PowerDNS server is unreachable") return false } if server.Version == nil || *server.Version == "" { fmt.Println("ERROR: Server returned empty version") return false } fmt.Printf("OK: PowerDNS %s is responding\n", *server.Version) return true ``` -------------------------------- ### Get Specific Server Information Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/servers.md Retrieves detailed information about a specific server using its virtual host ID. Useful for inspecting the configuration of a particular server instance. ```go server, err := client.Servers.Get(ctx, "localhost") if err != nil { log.Fatal(err) } fmt.Printf("Server: %s\n", *server.ID) fmt.Printf("Version: %s\n", *server.Version) fmt.Printf("Daemon Type: %s\n", *server.DaemonType) fmt.Printf("Config URL: %s\n", *server.ConfigURL) fmt.Printf("Zones URL: %s\n", *server.ZonesURL) ``` -------------------------------- ### Configure DNS UPDATE Access Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/metadata.md Allow specific IP addresses or subnets to send DNS UPDATE messages for dynamic DNS updates. This example configures access from an internal subnet. ```go // Allow updates from internal subnet _, err := client.Metadata.Set( ctx, "example.com", powerdns.MetadataAllowDNSUpdateFrom, []string{"192.168.0.0/16"}, ) if err != nil { log.Fatal(err) } fmt.Println("DNS UPDATE access configured") ``` -------------------------------- ### Initialize PowerDNS Client and Perform Operations Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Demonstrates initializing the PowerDNS client with a base URL, server name, and API key. It also shows how to list zones, add a record, and retrieve DNSSEC keys. ```go import ( "context" "github.com/joeig/go-powerdns/v3" ) // Initialize client client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw"), ) ctx := context.Background() // List zones zones, err := client.Zones.List(ctx) // Add a record err := client.Records.Add(ctx, "example.com", "www", powerdns.RRTypeA, 3600, []string{"192.0.2.1"}) // Manage DNSSEC keys, err := client.Cryptokeys.List(ctx, "example.com") ``` -------------------------------- ### Get Specific Record Type Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/records.md Use the Get method with a specific RRType to retrieve only records of that type for a given domain and name. This allows for targeted retrieval of DNS records. ```go aType := powerdns.RRTypeA rsets, err = client.Records.Get(ctx, "example.com", "www.example.com", &aType) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Verify Backend Configuration Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/config.md Check the configured database backend (e.g., MySQL, PostgreSQL, SQLite3, LDAP) and list the launched modules. ```go config, err := client.Config.List(ctx) if err != nil { log.Fatal(err) } settings := make(map[string]string) for _, setting := range config { if setting.Name != nil && setting.Value != nil { settings[*setting.Name] = *setting.Value } } // Check backend if backend, ok := settings["backend"]; ok { fmt.Printf("Database Backend: %s\n", backend) switch backend { case "mysql", "gmysql", "gpgsql": // Check database-specific settings fmt.Println("Relational database backend detected") case "sqlite3": fmt.Println("SQLite3 backend detected") case "ldap": fmt.Println("LDAP backend detected") } } // Check launched modules if launched, ok := settings["launch"]; ok { fmt.Printf("Launched modules: %s\n", launched) } ``` -------------------------------- ### List Zones Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Retrieves a list of all zones on the server. This method is useful for getting an overview of all configured DNS zones. ```APIDOC ## List Zones ### Description Retrieves a list of all zones on the server. ### Method GET ### Endpoint /zones ### Parameters #### Query Parameters - **ctx** (context.Context) - Required - Context for request cancellation and deadlines ### Response #### Success Response (200) - **[]Zone** - Slice of Zone structs representing all zones #### Response Example ```json [ { "id": 1, "name": "example.com.", "kind": "native", "dnssec": false, "serial": 1234567890, "notified_serial": 1234567890, "url": "/api/v1/servers/localhost/zones/1" } ] ``` ``` -------------------------------- ### Add Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Creates a new zone with pre-configured settings. ```APIDOC ## Add ### Description Creates a new zone with pre-configured settings. ### Method POST (Assumed based on creation operation) ### Endpoint `/zones` (Assumed, specific endpoint not provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **zone** (*Zone) - Required - Zone struct with configuration ### Request Example ```go zone := &powerdns.Zone{ Name: powerdns.String("example.com"), Kind: powerdns.ZoneKindPtr(powerdns.NativeZoneKind), DNSsec: powerdns.Bool(false), Nameservers: []string{"ns1.example.com."} } created, err := client.Zones.Add(ctx, zone) if err != nil { log.Fatal(err) } fmt.Printf("Zone created: %s\n", *created.Name) ``` ### Response #### Success Response (200) - **Zone** (*Zone) - The created zone object #### Response Example ```json { "id": "some-uuid", "name": "example.com", "kind": "NATIVE", "dnssec": false, "nameservers": ["ns1.example.com."] } ``` ``` -------------------------------- ### List All Zones Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Retrieves a list of all zones configured on the PowerDNS server. Use this to get an overview of all managed zones. ```go zones, err := client.Zones.List(ctx) if err != nil { log.Fatal(err) } for _, zone := range zones { fmt.Printf("Zone: %s (Kind: %s)\n", *zone.Name, *zone.Kind) } ``` -------------------------------- ### Initialize Docker Fixtures for PowerDNS Source: https://github.com/joeig/go-powerdns/blob/main/README.md Execute this command after launching the PowerDNS server with Docker Compose to initialize the fixtures. This script sets up the necessary data for testing. ```bash docker-compose -f docker-compose-v4.9.yml exec powerdns sh init_docker_fixtures.sh ``` -------------------------------- ### Get Records Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/records.md Retrieves DNS resource records for a given domain and name, optionally filtered by record type. ```APIDOC ## Get Records ### Description Retrieves DNS resource records. ### Method Get ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for request cancellation and deadlines - **domain** (string) - Required - Zone domain name - **name** (string) - Required - Full record name #### Query Parameters - **recordType** (*RRType) - Optional - DNS record type (nil to retrieve all types) ### Request Example ```go // Get all records for a name rrsets, err := client.Records.Get(ctx, "example.com", "www.example.com", nil) if err != nil { log.Fatal(err) } for _, rrset := range rrsets { fmt.Printf("Type: %s, TTL: %d\n", *rrset.Type, *rrset.TTL) for _, record := range rrset.Records { fmt.Printf(" Content: %s\n", *record.Content) } } // Get specific record type aType := powerdns.RRTypeA rrsets, err = client.Records.Get(ctx, "example.com", "www.example.com", &aType) if err != nil { log.Fatal(err) } ``` ### Response #### Success Response - **[]RRset** ([]RRset) - Slice of RRset structs matching the query #### Error Response - **error** (error) - Error if the request fails ``` -------------------------------- ### Initialize Client with Custom HTTP Client Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Use WithHTTPClient to provide a pre-configured http.Client for advanced customization of timeouts, TLS, and connection pooling. This option is useful for specific network configurations or performance tuning. ```go import ( "net" "net/http" "time" ) // Create custom HTTP client with specific settings httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ Dial: (&net.Dialer{ Timeout: 10 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, MaxIdleConns: 100, MaxIdleConnsPerHost: 10, }, } client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("apipw"), powerdns.WithHTTPClient(httpClient), ) ``` -------------------------------- ### List All Statistics Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/statistics.md Retrieves all available statistics from the PowerDNS server. Use this method to get a comprehensive overview of server metrics. ```go func (s *StatisticsService) List(ctx context.Context) ([]Statistic, error) ``` ```go stats, err := client.Statistics.List(ctx) if err != nil { log.Fatal(err) } for _, stat := range stats { fmt.Printf("Statistic: %s\n", *stat.Name) fmt.Printf(" Type: %s\n", *stat.Type) fmt.Printf(" Value: %v\n", stat.Value) } ``` -------------------------------- ### Initialize PowerDNS Client with API Key Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Demonstrates how to create a new PowerDNS client instance using an API key for authentication. The API key is sent as the X-API-Key HTTP header. ```go client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("your-api-key-here"), ) ``` -------------------------------- ### MetadataService.List Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/metadata.md Retrieves all metadata entries for a specified zone. This method is useful for getting an overview of all advanced behaviors configured for a zone. ```APIDOC ## MetadataService.List ### Description Retrieves all metadata entries for a zone. This method is useful for getting an overview of all advanced behaviors configured for a zone. ### Method Go SDK Method ### Parameters #### Path Parameters - **domain** (string) - Yes - Zone domain name (with or without trailing dot) #### Query Parameters - **ctx** (context.Context) - Yes - Context for request cancellation and deadlines ### Returns #### Success Response - **[]Metadata** - Slice of metadata entries for the zone #### Error Response - **error** - Error if the request fails ``` -------------------------------- ### Create Zone Object with Pointer Types in Go Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Shows how to correctly initialize a Zone object, ensuring that fields like Name, Kind, and DNSsec are set using pointer types as required by the library. Utilizes helper functions like powerdns.String, powerdns.ZoneKindPtr, and powerdns.Bool. ```go zone := &powerdns.Zone{ Name: powerdns.String("example.com"), Kind: powerdns.ZoneKindPtr(powerdns.NativeZoneKind), DNSsec: powerdns.Bool(true), } ``` -------------------------------- ### Get TSIG Key Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md Retrieves a specific TSIG key by its ID. This allows detailed inspection of a single key's properties. ```APIDOC ## Get TSIG Key ### Description Retrieves a specific TSIG key by its ID. ### Method `GET` ### Endpoint `/api/v1/tsigkeys/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the TSIG key to retrieve. ### Response #### Success Response (200 OK) - **TSIGKey** (object) - An object containing the details of the TSIG key. ``` -------------------------------- ### Get TSIG Key Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md Retrieves a specific TSIG key by its unique identifier or name. Use this to fetch details of an existing key. ```APIDOC ## Get TSIG Key ### Description Retrieves a specific TSIG key by ID or name. ### Method ```go func (t *TSIGKeysService) Get(ctx context.Context, id string) (*TSIGKey, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None #### Parameters - **id** (string) - Required - Key identifier or name (typically includes trailing dot, e.g., "examplekey.") ### Response #### Success Response (200) - **&TSIGKey** - TSIG key struct with detailed information #### Error Response - **error** - Error if the request fails ### Request Example ```go key, err := client.TSIGKeys.Get(ctx, "examplekey.") if err != nil { log.Fatal(err) } fmt.Printf("Key Name: %s\n", *key.Name) fmt.Printf("Algorithm: %s\n", *key.Algorithm) ``` ``` -------------------------------- ### Get Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Retrieves details for a specific zone by its domain name. Use this to inspect a particular zone's configuration and records. ```APIDOC ## Get Zone ### Description Retrieves details for a specific zone by domain name. ### Method GET ### Endpoint /zones/{domain} ### Parameters #### Path Parameters - **domain** (string) - Required - The zone domain name (with or without trailing dot) #### Query Parameters - **ctx** (context.Context) - Required - Context for request cancellation and deadlines ### Response #### Success Response (200) - **Zone** - Zone struct containing zone details and RRsets #### Response Example ```json { "id": 1, "name": "example.com.", "kind": "native", "dnssec": false, "serial": 1234567890, "notified_serial": 1234567890, "url": "/api/v1/servers/localhost/zones/1" } ``` ``` -------------------------------- ### Add New Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Creates a new zone with pre-configured settings. Pass a Zone struct containing the desired configuration. ```go zone := &powerdns.Zone{ Name: powerdns.String("example.com"), Kind: powerdns.ZoneKindPtr(powerdns.NativeZoneKind), DNSsec: powerdns.Bool(false), Nameservers: []string{"ns1.example.com."}, } created, err := client.Zones.Add(ctx, zone) if err != nil { log.Fatal(err) } fmt.Printf("Zone created: %s\n", *created.Name) ``` -------------------------------- ### Get a Specific Cryptokey Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/cryptokeys.md Retrieves a single cryptokey for a zone using its unique identifier. This is useful for inspecting the details of a particular key. ```go func (c *CryptokeysService) Get(ctx context.Context, domain string, id uint64) (*Cryptokey, error) ``` ```go key, err := client.Cryptokeys.Get(ctx, "example.com", 1337) if err != nil { log.Fatal(err) } fmt.Printf("Key Type: %s\n", *key.KeyType) fmt.Printf("Algorithm: %s\n", *key.Algorithm) fmt.Printf("Bits: %d\n", *key.Bits) // DS records for chain of trust for _, ds := range key.DS { fmt.Printf("DS Record: %s\n", ds) } ``` -------------------------------- ### List Cryptokeys for a Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/cryptokeys.md Retrieves all cryptokeys associated with a specified zone. Use this to get an overview of all keys used for signing and validation. ```go func (c *CryptokeysService) List(ctx context.Context, domain string) ([]Cryptokey, error) ``` ```go cryptokeys, err := client.Cryptokeys.List(ctx, "example.com") if err != nil { log.Fatal(err) } for _, key := range cryptokeys { fmt.Printf("Key ID: %d, Type: %s, Active: %v\n", *key.ID, *key.KeyType, *key.Active, ) } ``` -------------------------------- ### Import go-powerdns Source: https://github.com/joeig/go-powerdns/blob/main/README.md Import the go-powerdns library into your Go project. ```go import "github.com/joeig/go-powerdns/v3" ``` -------------------------------- ### Initialize Client with Custom Headers Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Use WithHeaders to add custom HTTP headers to all requests. This can be used alongside other authentication methods and overrides default headers like User-Agent. ```go client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithHeaders(map[string]string{ "X-Custom-Header": "custom-value", "User-Agent": "my-app/1.0", }), ) ``` -------------------------------- ### Get Cryptokey Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/cryptokeys.md Retrieves detailed information about a specific cryptokey for a zone, identified by its unique ID. This allows for inspection of individual key properties. ```APIDOC ## Get Cryptokey ### Description Retrieves a specific cryptokey for a zone. ### Method Get ### Parameters #### Path Parameters - **domain** (string) - Yes - Zone domain name - **id** (uint64) - Yes - Cryptokey identifier #### Query Parameters None #### Request Body None ### Request Example ```go key, err := client.Cryptokeys.Get(ctx, "example.com", 1337) if err != nil { log.Fatal(err) } fmt.Printf("Key Type: %s\n", *key.KeyType) fmt.Printf("Algorithm: %s\n", *key.Algorithm) fmt.Printf("Bits: %d\n", *key.Bits) // DS records for chain of trust for _, ds := range key.DS { fmt.Printf("DS Record: %s\n", ds) } ``` ### Response #### Success Response (200) - **Cryptokey** - Cryptokey struct with detailed information #### Response Example ```json { "ID": 1337, "KeyType": "ksk", "Active": true, "Algorithm": "rsasha256", "Bits": 4096, "DS": [ "12345 13 2 1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF" ] } ``` ``` -------------------------------- ### Perform Batch Record Operations in Go Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Illustrates how to prepare and send multiple DNS resource record changes in a single batch operation using the PATCH method. This is efficient for updating several records at once. ```go rrsets := &powerdns.RRsets{ Sets: []powerdns.RRset{ // Multiple records to add/modify }, } err := client.Records.Patch(ctx, "example.com", rrsets) ``` -------------------------------- ### Create New Master Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Creates a new master zone for which the PowerDNS server is authoritative. This example shows creation without DNSSEC enabled. ```go zone, err := client.Zones.AddMaster( ctx, "example.com", false, "", false, "", "", false, []string{"ns1.example.com."}, ) if err != nil { log.Fatal(err) } fmt.Printf("Master zone created: %s\n", *zone.Name) ``` -------------------------------- ### Manage Request Context with Timeout in Go Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Demonstrates how to create a context with a specified timeout for API requests. This ensures that operations do not hang indefinitely and helps manage resource usage. ```go // With timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() zone, err := client.Zones.Get(ctx, "example.com") ``` -------------------------------- ### List and Organize TSIG Keys Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md This snippet shows how to list all existing TSIG keys and then organize them by their respective algorithms. This is useful for monitoring and managing keys across different zones. ```go // List all TSIG keys keys, err := client.TSIGKeys.List(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Total TSIG keys: %d\n", len(keys)) // Organize by algorithm algorithms := make(map[string]int) for _, key := range keys { algo := *key.Algorithm algorithms[algo]++ } fmt.Println("Keys by algorithm:") for algo, count := range algorithms { fmt.Printf(" %s: %d\n", algo, count) } ``` -------------------------------- ### Get Specific Zone Details Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/zones.md Retrieves detailed information for a single zone by its domain name. Useful for inspecting a zone's configuration and RRsets. ```go zone, err := client.Zones.Get(ctx, "example.com") if err != nil { log.Fatal(err) } fmt.Printf("Zone Serial: %d\n", *zone.Serial) fmt.Printf("Zone Type: %s\n", *zone.Type) fmt.Printf("DNSSEC Enabled: %v\n", *zone.DNSsec) ``` -------------------------------- ### Configure PowerDNS Client with Environment Variables Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md This snippet shows the recommended pattern for configuring the PowerDNS client using environment variables for API key, base URL, and virtual host. It includes error handling for missing API keys and default values for URL and vHost. ```go import "os" apiKey := os.Getenv("POWERDNS_API_KEY") if apiKey == "" { log.Fatal("POWERDNS_API_KEY environment variable not set") } baseURL := os.Getenv("POWERDNS_URL") if baseURL == "" { baseURL = "http://localhost:8001" // default } vHost := os.Getenv("POWERDNS_VHOST") if vHost == "" { vHost = "localhost" // default } client := powerdns.New( baseURL, vHost, powerdns.WithAPIKey(apiKey), ) ``` -------------------------------- ### Production PowerDNS Client Configuration Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Recommended settings for production environments, including a custom HTTP client with a defined timeout and connection pooling. API key is fetched from an environment variable. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 10, DisableKeepAlives: false, }, } client := powerdns.New( "https://powerdns-api.example.com:8443", "primary-server", powerdns.WithAPIKey(os.Getenv("POWERDNS_API_KEY")), powerdns.WithHTTPClient(httpClient), powerdns.WithHeaders(map[string]string{ "X-Request-ID": uuid.New().String(), }), ) ``` -------------------------------- ### Handle Metadata Kind Not Found (404) Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/errors.md Handle a 404 status code when a requested metadata kind is not configured for a zone. Use `Metadata.List()` to check available metadata or `Create()` to set new metadata. ```go meta, err := client.Metadata.Get(ctx, "example.com", powerdns.MetadataAllowAXFRFrom) if err != nil { if apiErr, ok := err.(*powerdns.Error); ok && apiErr.StatusCode == 404 { log.Printf("Metadata not configured: %s", apiErr.Message) } } ``` -------------------------------- ### Get Specific Statistic Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/statistics.md Retrieves a specific statistic by its name from the PowerDNS server. Useful for monitoring individual metrics like query counts or cache performance. ```go func (s *StatisticsService) Get(ctx context.Context, statisticName string) ([]Statistic, error) ``` ```go // Get query count stats, err := client.Statistics.Get(ctx, "queries") if err != nil { log.Fatal(err) } if len(stats) > 0 { fmt.Printf("Queries: %v\n", stats[0].Value) } // Get packet cache hits stats, err = client.Statistics.Get(ctx, "packetcache-hits") if err != nil { log.Fatal(err) } if len(stats) > 0 { fmt.Printf("Packet Cache Hits: %v\n", stats[0].Value) } ``` -------------------------------- ### Define MetadataKind Type and Constants Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/types.md Defines a string type for metadata kinds and lists common constants. Use MetadataKindPtr to get a pointer to a MetadataKind value. ```go type MetadataKind string const ( MetadataAllowAXFRFrom MetadataKind = "ALLOW-AXFR-FROM" MetadataTSIGAllowAXFR MetadataKind = "TSIG-ALLOW-AXFR" MetadataAXFRMasterTSIG MetadataKind = "AXFR-MASTER-TSIG" MetadataSOAEdit MetadataKind = "SOA-EDIT" MetadataSOAEditAPI MetadataKind = "SOA-EDIT-API" // ... and 10+ more ) func MetadataKindPtr(v MetadataKind) *MetadataKind ``` -------------------------------- ### Initialize PowerDNS Client Source: https://github.com/joeig/go-powerdns/blob/main/README.md Initialize the PowerDNS client with the server address, virtual host, and API key. Supports context for cancellation and deadlines. ```go import ( "github.com/joeig/go-powerdns/v3" "context" ) // Let's say // * PowerDNS Authoritative Server is listening on `http://localhost:80`, // * the virtual host is `localhost` and // * the API key is `apipw`. pdns := powerdns.New("http://localhost:80", "localhost", powerdns.WithAPIKey("apipw")) // All API interactions support a Go context, which allow you to pass cancellation signals and deadlines. // If you don't need a context, `context.Background()` would be the right choice for the following examples. // If you want to learn more about how context helps you to build reliable APIs, see: https://go.dev/blog/context ctx := context.Background() ``` -------------------------------- ### Initialize PowerDNS Client Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/client.md Creates a new PowerDNS API client. Use functional options to customize authentication and headers. The `baseURL` and `vHost` are required parameters. ```go package main import ( "context" "github.com/joeig/go-powerdns/v3" ) func main() { client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("your-api-key"), ) ctx := context.Background() // Use the client zones, err := client.Zones.List(ctx) if err != nil { panic(err) } for _, zone := range zones { println(*zone.Name) } } ``` -------------------------------- ### Get Specific Zone Metadata Entry Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/metadata.md Retrieves a single metadata entry for a zone, identified by its kind. Useful for checking the configuration of a specific advanced behavior. ```go func (m *MetadataService) Get(ctx context.Context, domain string, kind MetadataKind) (*Metadata, error) ``` ```go meta, err := client.Metadata.Get(ctx, "example.com", powerdns.MetadataAllowAXFRFrom) if err != nil { log.Fatal(err) } fmt.Printf("ALLOW-AXFR-FROM: %v\n", meta.Metadata) ``` -------------------------------- ### Set Up Slave Zone Notifications Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/metadata.md Configure secondary servers to be notified of zone updates by specifying a list of servers or IP addresses that should receive these notifications. ```go // Notify these servers when zone changes _, err := client.Metadata.Set( ctx, "example.com", powerdns.MetadataAlsoNotify, []string{ "secondary1.example.com", "secondary2.example.com", "192.0.2.1", }, ) if err != nil { log.Fatal(err) } fmt.Println("Notification servers configured") ``` -------------------------------- ### Get TSIG Key by ID or Name Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/tsigkeys.md Retrieves a specific TSIG key using its identifier or name. Ensure the ID includes a trailing dot if it's a name. ```go key, err := client.TSIGKeys.Get(ctx, "examplekey.") if err != nil { log.Fatal(err) } fmt.Printf("Key Name: %s\n", *key.Name) fmt.Printf("Algorithm: %s\n", *key.Algorithm) ``` -------------------------------- ### Enable DNSSEC and List Cryptokeys for a Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/cryptokeys.md Enables DNSSEC for a zone if not already enabled, then lists and prints information about the active cryptokeys associated with that zone. Ensure the zone object is correctly retrieved and DNSSEC parameters are set before updating. ```go zone, err := client.Zones.Get(ctx, "example.com") if err != nil { log.Fatal(err) } if !*zone.DNSsec { zone.DNSsec = powerdns.Bool(true) zone.Nsec3Param = powerdns.String("1 0 1 aabbccdd") err = client.Zones.Change(ctx, "example.com", zone) if err != nil { log.Fatal(err) } } // List cryptokeys generated for the zone cryptokeys, err := client.Cryptokeys.List(ctx, "example.com") if err != nil { log.Fatal(err) } fmt.Printf("Zone has %d cryptokeys\n", len(cryptokeys)) for _, key := range cryptokeys { if *key.Active { fmt.Printf("Active %s key (ID: %d) with %d bits\n", *key.KeyType, *key.ID, *key.Bits, ) } } ``` -------------------------------- ### Initialize Go PowerDNS Client Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/README.md Initializes a new PowerDNS client. Requires the API endpoint, server name, and an API key for authentication. ```go client := powerdns.New("http://localhost:8001", "localhost", powerdns.WithAPIKey("key")) ``` -------------------------------- ### Export Configuration to File Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/config.md Save the current PowerDNS configuration to a text file for documentation or comparison purposes. Ensure the file is properly closed after writing. ```go config, err := client.Config.List(ctx) if err != nil { log.Fatal(err) } // Save to file file, err := os.Create("powerdns-config.txt") if err != nil { log.Fatal(err) } defer file.Close() writer := bufio.NewWriter(file) for _, setting := range config { if setting.Name != nil && setting.Value != nil { fmt.Fprintf(writer, "%s = %s\n", *setting.Name, *setting.Value) } } writer.Flush() fmt.Println("Configuration exported to powerdns-config.txt") ``` -------------------------------- ### Go - Search All Objects by Pattern Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/search.md Use this snippet to search for all object types (zones, records, comments) matching a given pattern. It returns up to a specified maximum number of results. ```go // Search for all objects matching a pattern results, err := client.Search.Data(ctx, "example*", 100, powerdns.SearchObjectTypeAll) if err != nil { log.Fatal(err) } for _, result := range results { fmt.Printf("Type: %s, Name: %s, Zone: %s\n", *result.ObjectType, *result.Name, *result.Zone, ) } ``` -------------------------------- ### Flush DNS Cache for a Domain Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/servers.md Flushes DNS cache entries for a specified domain on a given server. This is useful for ensuring that DNS changes are reflected immediately. The example also shows how to flush a specific record. ```go result, err := client.Servers.CacheFlush(ctx, "localhost", "example.com") if err != nil { log.Fatal(err) } fmt.Printf("Cache entries flushed: %d\n", *result.Count) fmt.Printf("Result: %s\n", *result.Result) // Flush specific record result, err = client.Servers.CacheFlush(ctx, "localhost", "www.example.com") if err != nil { log.Fatal(err) } fmt.Println("Record cache flushed successfully") ``` -------------------------------- ### View All Metadata for a Zone Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/metadata.md Retrieve and display all metadata settings configured for a specific zone. This is useful for auditing and understanding the current configuration. ```go metadata, err := client.Metadata.List(ctx, "example.com") if err != nil { log.Fatal(err) } fmt.Println("Zone metadata configuration:") for _, item := range metadata { fmt.Printf("\n%s:\n", *item.Kind) for _, val := range item.Metadata { fmt.Printf(" - %s\n", val) } } ``` -------------------------------- ### Request Server Information and Statistics Source: https://github.com/joeig/go-powerdns/blob/main/README.md Retrieve server statistics and lists of servers. ```go statistics, err := pdns.Statistics.List(ctx) servers, err := pdns.Servers.List(ctx) server, err := pdns.Servers.Get(ctx, "localhost") ``` -------------------------------- ### Add A Record Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/api-reference/records.md Use the Add method to create a new A record for a domain. Specify the domain, record name, type, TTL, and IP address content. ```go err := client.Records.Add( ctx, "example.com", "www.example.com", powerdns.RRTypeA, 3600, []string{"192.0.2.1"}, ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/configuration.md Use WithAPIKey to set the authentication key for PowerDNS API requests. This option adds the X-API-Key header to all outgoing requests. ```go client := powerdns.New( "http://localhost:8001", "localhost", powerdns.WithAPIKey("your-secret-api-key"), ) ``` -------------------------------- ### Launch PowerDNS Server with Docker Compose Source: https://github.com/joeig/go-powerdns/blob/main/README.md Use this command to launch a PowerDNS authoritative server with a generic SQLite3 backend, DNSSEC support, and optional fixtures. Ensure you have the correct docker-compose file for your PowerDNS version. ```bash docker-compose -f docker-compose-v4.9.yml up ``` -------------------------------- ### Handle TSIG Key Not Found (404) Source: https://github.com/joeig/go-powerdns/blob/main/_autodocs/errors.md Check for a 404 status code when a TSIG key is not found. Verify the key name for typos or use `TSIGKeys.List()` to confirm its existence. ```go key, err := client.TSIGKeys.Get(ctx, "nonexistent.") if err != nil { if apiErr, ok := err.(*powerdns.Error); ok && apiErr.StatusCode == 404 { log.Printf("TSIG key not found: %s", apiErr.Message) } } ```