Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions examples/Go/ConsoleApp/Example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Azure App Configuration Console Example

This example demonstrates how to use Azure App Configuration in a console/command-line application.

## Overview

This simple console application:

1. Loads configuration values from Azure App Configuration
2. Binds them to target configuration struct

## Running the Example

### Prerequisites

You need [an Azure subscription](https://azure.microsoft.com/free/) and the following Azure resources to run the examples:

- [Azure App Configuration store](https://learn.microsoft.com/en-us/azure/azure-app-configuration/quickstart-azure-app-configuration-create?tabs=azure-portal)

The examples retrieve credentials to access your App Configuration store from environment variables.
Alternatively, edit the source code to include the appropriate credentials.

### Add key-values

Add the following key-values to the App Configuration store and leave **Label** and **Content Type** with their default values. For more information about how to add key-values to a store using the Azure portal or the CLI, go to [Create a key-value](./quickstart-azure-app-configuration-create.md#create-a-key-value).

| Key | Value |
|------------------------|----------------|
| *Config.Message* | *Hello World!* |
| *Config.Font.Color* | *blue* |
| *Config.Font.Size* | *12* |

### Setup

1. Initialize a new Go module.

```bash
go mod init console-example-app
```
1. Add the Azure App Configuration provider as a dependency.

```bash
go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
```

1. Set the connection string as an environment variable:

```bash
# Windows
set AZURE_APPCONFIG_CONNECTION_STRING=your-connection-string

# Linux/macOS
export AZURE_APPCONFIG_CONNECTION_STRING=your-connection-string
```

### Run the Application

```bash
go run main.go
```
79 changes: 79 additions & 0 deletions examples/Go/ConsoleApp/Example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package main

import (
"context"
"fmt"
"log"
"os"
"time"

"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
)

type Config struct {
Font Font
Message string
}

type Font struct {
Color string
Size int
}

// loadConfiguration handles loading the configuration from Azure App Configuration
func loadConfiguration() (Config, error) {
// Get connection string from environment variable
connectionString := os.Getenv("AZURE_APPCONFIG_CONNECTION_STRING")

// Configuration setup
options := &azureappconfiguration.Options{
Selectors: []azureappconfiguration.Selector{
{
KeyFilter: "Config.*",
},
},
// Remove the prefix when mapping to struct fields
TrimKeyPrefixes: []string{"Config."},
}

authOptions := azureappconfiguration.AuthenticationOptions{
ConnectionString: connectionString,
}

// Create configuration provider with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

appCfgProvider, err := azureappconfiguration.Load(ctx, authOptions, options)
if err != nil {
return Config{}, err
}

// Parse configuration into struct
var config Config
err = appCfgProvider.Unmarshal(&config, nil)
if err != nil {
return Config{}, err
}

return config, nil
}

func main() {
fmt.Println("Azure App Configuration - Console Example")
fmt.Println("----------------------------------------")

// Load configuration
fmt.Println("Loading configuration from Azure App Configuration...")
config, err := loadConfiguration()
if err != nil {
log.Fatalf("Error loading configuration: %s", err)
}

// Display the configuration values
fmt.Println("\nConfiguration Values:")
fmt.Println("--------------------")
fmt.Printf("Font Color: %s\n", config.Font.Color)
fmt.Printf("Font Size: %d\n", config.Font.Size)
fmt.Printf("Message: %s\n", config.Message)
}
67 changes: 67 additions & 0 deletions examples/Go/ConsoleApp/Refresh/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Azure App Configuration Console Refresh Example

This example demonstrates how to use the refresh functionality of Azure App Configuration in a console/command-line application.

## Overview

This console application:

1. Loads configuration values from Azure App Configuration
2. Binds them to target configuration struct
3. Automatically refreshes the configuration when changed in Azure App Configuration

## Running the Example

### Prerequisites

You need [an Azure subscription](https://azure.microsoft.com/free/) and the following Azure resources to run the examples:

- [Azure App Configuration store](https://learn.microsoft.com/en-us/azure/azure-app-configuration/quickstart-azure-app-configuration-create?tabs=azure-portal)

The examples retrieve credentials to access your App Configuration store from environment variables.

### Add key-values

Add the following key-values to the App Configuration store and leave **Label** and **Content Type** with their default values:

| Key | Value |
|------------------------|----------------|
| *Config.Message* | *Hello World!* |
| *Config.Font.Color* | *blue* |
| *Config.Font.Size* | *12* |

### Setup

1. Initialize a new Go module.

```bash
go mod init console-example-refresh
```
1. Add the Azure App Configuration provider as a dependency.

```bash
go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
```

1. Set the connection string as an environment variable:

```bash
# Windows
set AZURE_APPCONFIG_CONNECTION_STRING=your-connection-string

# Linux/macOS
export AZURE_APPCONFIG_CONNECTION_STRING=your-connection-string
```

### Run the Application

```bash
go run main.go
```

### Testing the Refresh Functionality

1. Start the application
2. While it's running, modify the values in your Azure App Configuration store
3. Within 10 seconds (the configured refresh interval), the application should detect and apply the changes
4. You don't need to restart the application to see the updated values
137 changes: 137 additions & 0 deletions examples/Go/ConsoleApp/Refresh/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package main

import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"

"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
)

type Config struct {
Font Font
Message string
}

type Font struct {
Color string
Size int
}

// initializeAppConfiguration handles loading the configuration from Azure App Configuration
func initializeAppConfiguration() (*azureappconfiguration.AzureAppConfiguration, error) {
// Get connection string from environment variable
connectionString := os.Getenv("AZURE_APPCONFIG_CONNECTION_STRING")

// Options setup
options := &azureappconfiguration.Options{
Selectors: []azureappconfiguration.Selector{
{
KeyFilter: "Config.*",
},
},
// Remove the prefix when mapping to struct fields
TrimKeyPrefixes: []string{"Config."},
// Enable refresh every 10 seconds
RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{
Enabled: true,
Interval: 10 * time.Second,
},
}

authOptions := azureappconfiguration.AuthenticationOptions{
ConnectionString: connectionString,
}

// Create configuration provider with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

return azureappconfiguration.Load(ctx, authOptions, options)
}

// displayConfig prints the current configuration values
func displayConfig(config Config) {
fmt.Println("\nCurrent Configuration Values:")
fmt.Println("--------------------")
fmt.Printf("Font Color: %s\n", config.Font.Color)
fmt.Printf("Font Size: %d\n", config.Font.Size)
fmt.Printf("Message: %s\n", config.Message)
fmt.Println("--------------------")
}

func main() {
fmt.Println("Azure App Configuration - Console Refresh Example")
fmt.Println("----------------------------------------")

// Load configuration
fmt.Println("Loading configuration from Azure App Configuration...")
appCfgProvider, err := initializeAppConfiguration()
if err != nil {
log.Fatalf("Error loading configuration: %s", err)
}

// Parse initial configuration into struct
var config Config
err = appCfgProvider.Unmarshal(&config, nil)
if err != nil {
log.Fatalf("Error unmarshalling configuration: %s", err)
}

// Display the initial configuration
displayConfig(config)

// Register refresh callback to update and display the configuration
appCfgProvider.OnRefreshSuccess(func() {
fmt.Println("\n🔄 Configuration changed! Updating values...")

// Re-unmarshal the configuration
var updatedConfig Config
err := appCfgProvider.Unmarshal(&updatedConfig, nil)
if err != nil {
log.Printf("Error unmarshalling updated configuration: %s", err)
return
}

// Update our working config
config = updatedConfig

// Display the updated configuration
displayConfig(config)
})

// Setup a channel to listen for termination signals
done := make(chan os.Signal, 1)
signal.Notify(done, syscall.SIGINT, syscall.SIGTERM)

fmt.Println("\nWaiting for configuration changes...")
fmt.Println("(Update values in Azure App Configuration to see refresh in action)")
fmt.Println("Press Ctrl+C to exit")

// Start a ticker to periodically trigger refresh
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()

// Keep the application running until terminated
for {
select {
case <-ticker.C:
// Trigger refresh in background
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := appCfgProvider.Refresh(ctx); err != nil {
log.Printf("Error refreshing configuration: %s", err)
}
}()
case <-done:
fmt.Println("\nExiting...")
return
}
}
}
Loading