Skip to content

Commit 22b4bc7

Browse files
Document exported fields (#13)
* add doc for exported fields * update * update * update comments * update example * add package comment
1 parent dafb31b commit 22b4bc7

3 files changed

Lines changed: 196 additions & 13 deletions

File tree

azureappconfiguration.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

4+
// Package azureappconfiguration provides a client for Azure App Configuration, enabling Go applications
5+
// to manage application settings with Microsoft's Azure App Configuration service.
6+
//
7+
// The azureappconfiguration package allows loading configuration data from Azure App Configuration in a structured way,
8+
// with support for automatic Key Vault reference resolution, hierarchical configuration construction,
9+
// and strongly typed configuration binding.
10+
//
11+
// For more information about Azure App Configuration, see:
12+
// https://learn.microsoft.com/en-us/azure/azure-app-configuration/
413
package azureappconfiguration
514

615
import (
@@ -17,6 +26,7 @@ import (
1726
"golang.org/x/sync/errgroup"
1827
)
1928

29+
// An AzureAppConfiguration is a configuration provider that stores and manages settings sourced from Azure App Configuration.
2030
type AzureAppConfiguration struct {
2131
keyValues map[string]any
2232
kvSelectors []Selector
@@ -26,6 +36,17 @@ type AzureAppConfiguration struct {
2636
resolver *keyVaultReferenceResolver
2737
}
2838

39+
// Load initializes a new AzureAppConfiguration instance and loads the configuration data from
40+
// Azure App Configuration service.
41+
//
42+
// Parameters:
43+
// - ctx: The context for the operation.
44+
// - authentication: Authentication options for connecting to the Azure App Configuration service
45+
// - options: Configuration options to customize behavior, such as key filters and prefix trimming
46+
//
47+
// Returns:
48+
// - A configured AzureAppConfiguration instance that provides access to the loaded configuration data
49+
// - An error if the operation fails, such as authentication errors or connectivity issues
2950
func Load(ctx context.Context, authentication AuthenticationOptions, options *Options) (*AzureAppConfiguration, error) {
3051
if err := verifyAuthenticationOptions(authentication); err != nil {
3152
return nil, err
@@ -58,6 +79,18 @@ func Load(ctx context.Context, authentication AuthenticationOptions, options *Op
5879
return azappcfg, nil
5980
}
6081

82+
// Unmarshal parses the configuration and stores the result in the value pointed to v. It builds a hierarchical configuration structure based on key separators.
83+
// It supports converting values to appropriate target types.
84+
//
85+
// Fields in the target struct are matched with configuration keys using the field name by default.
86+
// For custom field mapping, use json struct tags.
87+
//
88+
// Parameters:
89+
// - v: A pointer to the struct to populate with configuration values
90+
// - options: Optional parameters (e,g, separator) for controlling the unmarshalling behavior
91+
//
92+
// Returns:
93+
// - An error if unmarshalling fails due to type conversion issues or invalid configuration
6194
func (azappcfg *AzureAppConfiguration) Unmarshal(v any, options *ConstructionOptions) error {
6295
if options == nil || options.Separator == "" {
6396
options = &ConstructionOptions{
@@ -88,6 +121,15 @@ func (azappcfg *AzureAppConfiguration) Unmarshal(v any, options *ConstructionOpt
88121
return decoder.Decode(azappcfg.constructHierarchicalMap(options.Separator))
89122
}
90123

124+
// GetBytes returns the configuration as a JSON byte array with hierarchical structure.
125+
// This method is particularly useful for integrating with "encoding/json" package or third-party configuration packages like Viper or Koanf.
126+
//
127+
// Parameters:
128+
// - options: Optional parameters for controlling JSON construction, particularly the key separator
129+
//
130+
// Returns:
131+
// - A byte array containing the JSON representation of the configuration
132+
// - An error if JSON marshalling fails or if an invalid separator is specified
91133
func (azappcfg *AzureAppConfiguration) GetBytes(options *ConstructionOptions) ([]byte, error) {
92134
if options == nil || options.Separator == "" {
93135
options = &ConstructionOptions{

example_test.go

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
//go:build examples
2+
// +build examples
3+
4+
// Copyright (c) Microsoft Corporation.
5+
// Licensed under the MIT License.
6+
7+
package azureappconfiguration_test
8+
9+
import (
10+
"context"
11+
"fmt"
12+
"log"
13+
"os"
14+
15+
"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
16+
)
17+
18+
func ExampleLoad() {
19+
// Get the endpoint from environment variable
20+
endpoint := os.Getenv("AZURE_APPCONFIG_ENDPOINT")
21+
if endpoint == "" {
22+
log.Fatal("AZURE_APPCONFIG_ENDPOINT environment variable not set")
23+
}
24+
25+
// Create a credential using DefaultAzureCredential
26+
credential, err := azidentity.NewDefaultAzureCredential(nil)
27+
if err != nil {
28+
log.Fatalf("Failed to create credential: %v", err)
29+
}
30+
31+
// Set up authentication options with endpoint and credential
32+
authOptions := azureappconfiguration.AuthenticationOptions{
33+
Endpoint: endpoint,
34+
Credential: credential,
35+
}
36+
37+
// Create a context
38+
ctx := context.Background()
39+
40+
// Load configuration with default options
41+
provider, err := azureappconfiguration.Load(ctx, authOptions, nil)
42+
if err != nil {
43+
log.Fatalf("Failed to load configuration: %v", err)
44+
}
45+
46+
// Use the provider...
47+
fmt.Printf("Configuration loaded successfully: %v\n", provider != nil)
48+
49+
// Output:
50+
// Configuration loaded successfully: true
51+
}
52+
53+
func ExampleAzureAppConfiguration_Unmarshal() {
54+
// Assume we have already loaded the provider
55+
provider, _ := loadExampleProvider()
56+
57+
// Define a configuration structure
58+
type ServerConfig struct {
59+
Port int `json:"port"`
60+
Host string `json:"host"`
61+
Debug bool `json:"debug"`
62+
Timeout int `json:"timeout"`
63+
Tags []string `json:"tags"`
64+
}
65+
66+
// Unmarshal into the struct
67+
var config ServerConfig
68+
err := provider.Unmarshal(&config, nil)
69+
if err != nil {
70+
log.Fatalf("Failed to unmarshal configuration: %v", err)
71+
}
72+
73+
fmt.Printf("Server will run at %s:%d\n", config.Host, config.Port)
74+
fmt.Printf("Debug mode: %v, Timeout: %d seconds\n", config.Debug, config.Timeout)
75+
fmt.Printf("Tags: %v\n", config.Tags)
76+
77+
// Output:
78+
// Server will run at localhost:8080
79+
// Debug mode: true, Timeout: 30 seconds
80+
// Tags: [production primary]
81+
}
82+
83+
func ExampleAzureAppConfiguration_GetBytes() {
84+
// Assume we have already loaded the provider
85+
provider, _ := loadExampleProvider()
86+
87+
// Get configuration as JSON bytes
88+
jsonBytes, err := provider.GetBytes(&azureappconfiguration.ConstructionOptions{
89+
Separator: ":", // Use ":" as the separator in hierarchical keys
90+
})
91+
if err != nil {
92+
log.Fatalf("Failed to get configuration as bytes: %v", err)
93+
}
94+
95+
// Print the JSON string for demonstration
96+
fmt.Println(string(jsonBytes))
97+
98+
// Output would be JSON like:
99+
// {"database":{"host":"localhost","port":5432,"username":"admin"},"debug":true,"timeout":30}
100+
}
101+
102+
// Helper function to simulate loading a provider for examples
103+
func loadExampleProvider() (*azureappconfiguration.AzureAppConfiguration, error) {
104+
// Since we can't actually connect in an example, this is just a placeholder
105+
return nil, nil // In real examples, this would return a valid provider
106+
}

options.go

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,48 +12,83 @@ import (
1212
)
1313

1414
// Options contains optional parameters to configure the behavior of an Azure App Configuration provider.
15-
// If selectors are not provided, all key-values with no label are loaded.
15+
// It provides control over which key-values to fetch, how to trim key prefixes, and how to handle Key Vault references.
1616
type Options struct {
17-
// Trims the provided prefixes from the keys of all key-values retrieved from Azure App Configuration.
17+
// TrimKeyPrefixes specifies a list of prefixes to trim from the keys of all key-values
18+
// retrieved from Azure App Configuration, making them more suitable for binding to structured types.
1819
TrimKeyPrefixes []string
20+
21+
// Selectors defines what key-values to load from Azure App Configuration
22+
// Each selector combines a key filter and label filter
23+
// If selectors are not provided, all key-values with no label are loaded by default.
1924
Selectors []Selector
25+
26+
// KeyVaultOptions configures how Key Vault references are resolved.
2027
KeyVaultOptions KeyVaultOptions
28+
29+
// ClientOptions provides options for configuring the underlying Azure App Configuration client.
2130
ClientOptions *azappconfig.ClientOptions
2231
}
2332

24-
// AuthenticationOptions contains optional parameters to construct an Azure App Configuration client
25-
// ConnectionString or endpoint with credential must be be provided
33+
// AuthenticationOptions contains parameters for authenticating with the Azure App Configuration service.
34+
// Either a connection string or an endpoint with credential must be provided.
2635
type AuthenticationOptions struct {
36+
// Credential is a token credential for Azure EntraID Authenticaiton.
37+
// Required when Endpoint is provided.
2738
Credential azcore.TokenCredential
39+
40+
// Endpoint is the URL of the Azure App Configuration service.
41+
// Required when using token-based authentication with Credential.
2842
Endpoint string
43+
44+
// ConnectionString is the connection string for the Azure App Configuration service.
2945
ConnectionString string
3046
}
3147

32-
// Selector specifies what key-values to include in the configuration provider.
48+
// Selector specifies what key-values to load from Azure App Configuration.
3349
type Selector struct {
50+
// KeyFilter specifies which keys to retrieve from Azure App Configuration.
51+
// It can include wildcards, e.g. "app*" will match all keys starting with "app".
3452
KeyFilter string
53+
54+
// LabelFilter specifies which labels to retrieve from Azure App Configuration.
55+
// Empty string or omitted value will use the default no-label filter.
56+
// Note: Wildcards are not supported in label filters.
3557
LabelFilter string
3658
}
3759

38-
// SecretResolver is an interface to resolve secret from key vault reference
60+
// SecretResolver is an interface to resolve secrets from Key Vault references.
61+
// Implement this interface to provide custom secret resolution logic.
3962
type SecretResolver interface {
40-
// keyVaultReference: "https://{keyVaultName}.vault.azure.net/secrets/{secretName}/{secretVersion}"
63+
// ResolveSecret resolves a Key Vault reference URL to the actual secret value.
64+
//
65+
// Parameters:
66+
// - ctx: The context for the operation
67+
// - keyVaultReference: A URL in the format "https://{keyVaultName}.vault.azure.net/secrets/{secretName}/{secretVersion}"
68+
//
69+
// Returns:
70+
// - The resolved secret value as a string
71+
// - An error if the secret could not be resolved
4172
ResolveSecret(ctx context.Context, keyVaultReference url.URL) (string, error)
4273
}
4374

44-
// KeyVaultOptions contains optional parameters to configure the behavior of key vault reference resolution
75+
// KeyVaultOptions contains parameters to configure the build-in Key Vault reference resolution.
76+
// These options determine how the provider will authenticate with and retrieve
4577
type KeyVaultOptions struct {
46-
// Credential specifies the token credential used to authenticate to key vaults
78+
// Credential specifies the token credential used to authenticate to Azure Key Vault services.
79+
// This is required for Key Vault reference resolution unless a custom SecretResolver is provided.
4780
Credential azcore.TokenCredential
4881

49-
// SecretResolver specifies the callback used to resolve key vault references
82+
// SecretResolver specifies a custom implementation for resolving Key Vault references.
83+
// When provided, this takes precedence over using the default resolver with Credential.
5084
SecretResolver SecretResolver
5185
}
5286

53-
// ConstructionOptions contains optional parameters for Unmarshal and GetBytes methods
87+
// ConstructionOptions contains parameters for parsing keys with hierarchical structure.
5488
type ConstructionOptions struct {
55-
// Separator is used to unmarshal configuration when the keys themselves contain the separator
89+
// Separator specifies the character used to determine hierarchy in configuration keys
90+
// when mapping to nested struct fields during unmarshaling operations.
5691
// Supported values: '.', ',', ';', '-', '_', '__', '/', ':'.
57-
// If not provided, the default separator "." will be used
92+
// If not provided, the default separator "." will be used.
5893
Separator string
5994
}

0 commit comments

Comments
 (0)