Go 組態提供者

Azure 應用程式組態是一項受控服務,可協助開發人員簡單且安全地集中管理其應用程式組態。 Go 組態提供者程式庫會以受控方式,從 Azure 應用程式組態存放區載入組態。 此用戶端程式庫會在 Azure SDK for Go 上新增其他功能。

載入設定

Azure 應用程式組態 Go 提供者可讓您將組態值從 Azure 應用程式組態存放區載入 Go 應用程式。 您可以使用 Microsoft Entra ID 驗證或連線字串來連線。

若要使用 Go 組態提供者,請安裝套件:

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

您可以從 Load 套件呼叫 azureappconfiguration 函式,以從 Azure 應用程式組態載入設定。 Load 函式會接受驗證選項和設定選項,以自訂載入行為。

您可以使用 DefaultAzureCredential或任何其他 令牌認證實作,向應用程式組態存放區進行驗證。 請依照 指示 將您的憑證指派為 應用程式設定數據讀取者 角色。

package main

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

	"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {
	ctx := context.Background()
	
	// Get the endpoint from environment variable
	endpoint := os.Getenv("AZURE_APPCONFIG_ENDPOINT")
	
	// Create a credential using DefaultAzureCredential
	credential, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("Failed to create credential: %v", err)
	}

	// Set up authentication options
	authOptions := azureappconfiguration.AuthenticationOptions{
		Endpoint:   endpoint,
		Credential: credential,
	}

	// Load configuration from Azure App Configuration
	appConfig, err := azureappconfiguration.Load(ctx, authOptions, nil)
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}
}

使用選取器載入特定索引鍵/值

根據預設,組態提供者會從應用程式組態載入不含標籤的所有索引鍵/值。 您可以透過在 Selectors 結構中設定 Options 欄位來選擇性地載入索引鍵-值。

options := &azureappconfiguration.Options{
	Selectors: []azureappconfiguration.Selector{
		{
			// Load configuration values with prefix "App:" and no label
			KeyFilter:   "App:*",
			LabelFilter: "",
		},
		{
			// Load configuration values with prefix "App:" and "Prod" label
			KeyFilter:   "App:*",
			LabelFilter: "Prod",
		},
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

Selector 結構支援下列欄位:

  • KeyFilter:判斷要包含的組態索引鍵。 使用完全相符、前置詞符合 * 或以逗號分隔的多個索引鍵。
  • LabelFilter:選取具有特定標籤的索引鍵-值。 如果空白,則載入沒有標籤的索引鍵-值。

備註

當多個選取器包含重疊的索引鍵時,較後的選取器會優先於較早的選取器。

標籤篩選

參數 TagFilters 選擇帶有特定標籤的鍵值。 只有當篩選中指定的所有標記和對應的值都符合時,才會載入鍵值。

options := &azureappconfiguration.Options{
	Selectors: []azureappconfiguration.Selector{
		{
			// Load configuration values with prefix "App:" and specific tags
			KeyFilter:   "App:*",
			TagFilters: []string{"env=prod"},
		},
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

備註

字元星號 (*)、逗號 (,) 和反斜線 (\) 為保留字元,在標籤篩選器中使用時必須以反斜線進行跳脫。

從索引鍵修剪前置詞

載入具有特定前置詞的組態值時,您可以使用 TrimKeyPrefixes 選項從組態的索引鍵中移除這些前置詞。 這會在應用程式中建立更簡潔的設定密鑰,同時維護應用程式組態存放區中的組織。

options := &azureappconfiguration.Options{
	// Load configuration values with prefix "TestApp:" and trim the prefix
	Selectors: []azureappconfiguration.Selector{
		{
			KeyFilter: "TestApp:*",
		},
	},
	TrimKeyPrefixes: []string{"TestApp:"},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

例如,如果您的應用程式組態存放區包含名為 TestApp:Settings:Message 的索引鍵,則在修剪 Settings:Message 前置詞後,可以在您的應用程式中存取為 TestApp:。

JSON 內容類型處理

您可以在應用程式組態中建立 JSON 索引鍵/值。 讀取具有內容類型 "application/json" 的索引鍵值時,組態提供者會將其剖析為巢狀結構。 如需詳細資訊,請移至 使用內容類型在應用程式組態中儲存 JSON 索引鍵/值。

備註

從 版本 1.2.0 開始,設定提供者允許在具有 型別之內容的鍵值中,加入以 (application/json) 定義的註解。

取用設定

AzureAppConfiguration 函式傳回的 Load 類型提供數個方法來存取您的組態資料:

解除封送處理至結構

Unmarshal 方法提供了一種類型安全的方式,來將組態值載入到 Go 結構中。 此方法可以防止因組態索引鍵輸入錯誤而導致執行階段錯誤,並使您的程式碼更易於維護。 方法會接受選用的 ConstructionOptions 參數,以自訂組態索引鍵對應至結構欄位的方式。

type Config struct {
	Message string
	App     struct {
		Name     string
		Debug    bool
		Settings struct {
			Timeout    int
			RetryCount int
		}
	}
}

func main() {
	// ... load configuration ...
	
	// Create a configuration struct and unmarshal into it
	var config Config
	if err := appConfig.Unmarshal(&config, nil); err != nil {
		log.Fatalf("Failed to unmarshal configuration: %v", err)
	}

	// Access configuration values
	fmt.Printf("Message: %s\n", config.Message)
	fmt.Printf("App Name: %s\n", config.App.Name)
	fmt.Printf("Debug Mode: %t\n", config.App.Debug)
	fmt.Printf("Timeout: %d seconds\n", config.App.Settings.Timeout)
}

自訂索引鍵分隔符號

您可以使用 ConstructionOptions 來自訂組態索引鍵對應至結構欄位的方式。 當您的組態索引鍵使用與預設的句點 (.) 不同的分隔符號時,這很有用:

// Configuration keys using colon separator: "App:Name", "App:Settings:Timeout"
constructionOptions := &azureappconfiguration.ConstructionOptions{
	Separator: ":",
}

var config Config
if err := appConfig.Unmarshal(&config, constructionOptions); err != nil {
	log.Fatalf("Failed to unmarshal configuration: %v", err)
}

ConstructionOptions 結構支援下列分隔符號:.、,、;、-、_、__、/、:。 如果未指定,則會使用預設分隔符號 .。

取得原始 JSON 位元組

GetBytes 方法會將您的組態擷取為原始 JSON 資料,為與 JSON 處理程式庫或組態框架 (如 viper) 整合提供了靈活性。 此方法也會接受選用的 ConstructionOptions 參數來控制索引鍵階層的對應。

// Get configuration as JSON bytes with default separator
jsonBytes, err := appConfig.GetBytes(nil)
if err != nil {
	log.Fatalf("Failed to get configuration as bytes: %v", err)
}

fmt.Println("Raw JSON Configuration:")
fmt.Println(string(jsonBytes))

// Get configuration with custom separator
constructionOptions := &azureappconfiguration.ConstructionOptions{
	Separator: ":",
}
jsonBytes, err = appConfig.GetBytes(constructionOptions)
if err != nil {
	log.Fatalf("Failed to get configuration as bytes: %v", err)
}

// Example: Use with viper
v := viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewBuffer(jsonBytes)); err != nil {
	log.Fatalf("Failed to read config into viper: %v", err)
}

設定重新整理

設定重新整理可讓應用程式從應用程式組態存放區提取最新的值,而不需要重新啟動。 您可以在 RefreshOptions 結構中使用 Options 欄位來設定重新整理選項。 當伺服器上偵測到已選取索引鍵/值的任何變更時,將會更新載入的組態。 根據預設,會使用 30 秒的重新整理間隔,但您可以使用 Interval 屬性來覆寫。

options := &azureappconfiguration.Options{
	// Load all keys that start with `TestApp:` and have no label
	Selectors: []azureappconfiguration.Selector{
		{
			KeyFilter:   "TestApp:*",
			LabelFilter: "",
		},
	},
	// Trigger full configuration refresh when any selected key changes
	RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{
		Enabled:  true,
		// Check for changes no more often than every 60 seconds
		Interval: 60 * time.Second,
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

單獨設定 RefreshOptions 不會自動重新整理組態。 您需要在 Refresh 執行個體上呼叫 AzureAppConfiguration 方法來觸發重新整理。

// Trigger a refresh
if err := appConfig.Refresh(ctx); err != nil {
	log.Printf("Failed to refresh configuration: %v", err)
}

此設計可防止應用程式閒置時,應用程式組態的不必要要求。 您應該包含應用程式活動發生所在的 Refresh 呼叫。 這稱為活動驅動組態重新整理。 例如,您可以在處理傳入要求時或在執行複雜工作的反覆項目內呼叫 Refresh。

備註

即使重新整理呼叫因任何原因而導致失敗,您的應用程式仍會繼續使用快取設定。 當設定的重新整理間隔通過時,將會進行另一次嘗試,而重新整理呼叫是由應用程式活動所觸發。 在設定的重新整理的間隔過去之前,呼叫 Refresh 是不可操作的,因此即使頻繁呼叫,其對效能的影響也是最小的。

重新整理 Sentinel 索引鍵

Sentinel 索引鍵是您完成所有其他索引鍵變更之後才更新的索引鍵。 設定提供者會監視 Sentinel 索引鍵,而不是所有選取的索引鍵/值。 偵測到變更時,您的應用程式會重新整理所有設定值。

此方法在更新多個鍵值時很有用。 只有在完成所有其他組態變更之後,才會更新 sentinel 金鑰,以確保應用程式只會重載設定一次,維持一致性。

options := &azureappconfiguration.Options{
	// Load all keys that start with `TestApp:` and have no label
	Selectors: []azureappconfiguration.Selector{
		{
			KeyFilter:   "TestApp:*",
			LabelFilter: "",
		},
	},
	// Trigger full configuration refresh only if the `SentinelKey` changes
	RefreshOptions:  azureappconfiguration.KeyValueRefreshOptions{
		Enabled: true,
		WatchedSettings: []azureappconfiguration.WatchedSetting{
			{
				Key:   "SentinelKey",
				Label: "",
			},
		},
	},
}

自訂重新整理回呼

OnRefreshSuccess 方法會註冊回呼函式,每當組態成功重新整理設定並偵測到實際變更時,就會執行該函式。

var config Config
if err := appConfig.Unmarshal(&config, nil); err != nil {
    log.Fatalf("Failed to unmarshal configuration: %v", err)
}

// Register refresh callback
appConfig.OnRefreshSuccess(func() {
    // Re-unmarshal the configuration
    err := appConfig.Unmarshal(&config, nil)
    if err != nil {
        log.Printf("Failed to unmarshal updated configuration: %s", err)
        return
    }
})

功能旗標

Azure 應用程式組態中的功能旗標提供新式方法來控制應用程式中的功能可用性。 與一般組態值不同,必須在 FeatureFlagOptions 結構中使用 Options 欄位明確載入功能旗標。

options := &azureappconfiguration.Options{
	FeatureFlagOptions: azureappconfiguration.FeatureFlagOptions{
		Enabled: true,
		// Load feature flags that start with `TestApp:` and have `dev` label
		Selectors: []azureappconfiguration.Selector{
			{
				KeyFilter:   "TestApp:*",
				LabelFilter: "dev",
			},
		},
		RefreshOptions: azureappconfiguration.RefreshOptions{
			Enabled:  true,
			Interval: 60 * time.Second,
		},
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

小提示

在 FeatureFlagOptions 中未指定選取器時,其會載入應用程式組態存放區中沒有標籤的所有功能旗標。 功能旗標的預設重新整理的間隔是 30 秒。

這很重要

若要有效地取用和管理從 Azure 應用程式組態載入的功能旗標,請安裝和使用 featuremanagement 套件。 此程式庫提供了一種結構化的方式來控制應用程式的功能行為。

功能管理

功能管理 Go 程式庫提供結構化的方式,以根據功能旗標來開發和公開應用程式功能。 功能管理程式庫的設計目的是要與設定提供者程式庫搭配運作。

若要使用功能旗標搭配功能管理程式庫,請安裝必要的套件:

go get github.com/microsoft/Featuremanagement-Go/featuremanagement
go get github.com/microsoft/Featuremanagement-Go/featuremanagement/providers/azappconfig

下列範例示範如何將功能管理程式庫與組態提供者整合,以動態控制功能可用性:

import (
	"github.com/microsoft/Featuremanagement-Go/featuremanagement"
	"github.com/microsoft/Featuremanagement-Go/featuremanagement/providers/azappconfig"
)

func main() {
	// Set up authentication options
	authOptions := azureappconfiguration.AuthenticationOptions{
		Endpoint:   endpoint,
		Credential: credential,
	}

	// Load configuration with feature flags enabled
	options := &azureappconfiguration.Options{
		FeatureFlagOptions: azureappconfiguration.FeatureFlagOptions{
			Enabled: true,
			RefreshOptions: azureappconfiguration.RefreshOptions{
				Enabled: true,
			},
		},
	}

	appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// Create feature flag provider using the Azure App Configuration
	featureFlagProvider, err := azappconfig.NewFeatureFlagProvider(appConfig)
	if err != nil {
		log.Fatalf("Error creating feature flag provider: %v", err)
	}

	// Create feature manager
	featureManager, err := featuremanagement.NewFeatureManager(featureFlagProvider, nil)
	if err != nil {
		log.Fatalf("Error creating feature manager: %v", err)
	}

	// Use the feature manager to check feature flags
	isEnabled, err := featureManager.IsEnabled("Beta")
	if err != nil {
		log.Printf("Error checking feature flag: %v", err)
		return
	}

	if isEnabled {
		fmt.Println("Beta feature is enabled!")
		// Execute beta functionality
	} else {
		fmt.Println("Beta feature is disabled")
		// Execute standard functionality
	}
}

如需如何使用 Go 功能管理程式庫的詳細資訊,請移至功能旗標快速入門。

金鑰保存庫 參考

Azure 應用程式組態支援參考儲存在 Azure Key Vault 中的祕密。 在 [應用程式組態] 中,您可以建立對應至儲存在 金鑰保存庫 中的袐密的金鑰,但一旦載入,就可以像任何其他組態一樣存取。

組態提供者程式庫會擷取 金鑰保存庫 參考,就像針對儲存在應用程式組態中的任何其他索引鍵一樣。 您必須在 KeyVaultOptions 結構中使用 Options 欄位來設定 金鑰保存庫 存取。

連線到 金鑰保存庫

您可以藉由提供可向 金鑰保存庫 執行個體進行驗證的認證來設定 金鑰保存庫 存取。

import (
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

// Create a credential for Key Vault access
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
	log.Fatalf("Failed to create credential: %v", err)
}

options := &azureappconfiguration.Options{
	KeyVaultOptions: azureappconfiguration.KeyVaultOptions{
		Credential: credential,
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

自訂密鑰解析器

您也可以提供自訂袐密解析程式函式,以在預設認證型方法不適用時處理 金鑰保存庫 參考:

options := &azureappconfiguration.Options{
	KeyVaultOptions: azureappconfiguration.KeyVaultOptions{
		SecretResolver: func(ctx context.Context, keyVaultReference url.URL) (string, error) {
			// Custom logic to resolve secrets
			// This could integrate with your existing secret management system
			// or provide fallback values for development environments
			
			if isDevelopment {
				return os.Getenv("FALLBACK_SECRET_VALUE"), nil
			}
			
			// Implement your custom secret retrieval logic here
			return retrieveSecret(keyVaultReference)
		},
	},
}

這很重要

如果您的應用程式載入包含 金鑰保存庫 參考的索引鍵-值,而沒有適當的 金鑰保存庫 組態,則在載入作業期間會傳回錯誤。 確保您已正確設定 金鑰保存庫 存取或袐密解析程式。

金鑰保存庫 祕密重新整理

Azure 應用程式組態可讓您設定與設定重新整理周期無關的秘密重新整理間隔。 這對安全性至關重要,因為雖然應用程式組態中的 金鑰保存庫 參考 URI 保持不變,但 金鑰保存庫 中的基礎秘密可能會輪替作為安全性做法的一部分。

若要確保您的應用程式一律使用最新的袐密值,請在 RefreshOptions 結構中設定 KeyVaultOptions 欄位。

import (
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

// Create a credential for Key Vault access
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
	log.Fatalf("Failed to create credential: %v", err)
}

options := &azureappconfiguration.Options{
	KeyVaultOptions: azureappconfiguration.KeyVaultOptions{
		Credential: credential,
		RefreshOptions: azureappconfiguration.RefreshOptions{
			Enabled: true,
			Interval: 5 * time.Minute,
		},
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

快照

快照集是應用程式組態存放區索引鍵/值的不可變具名子集。 建立過程中會透過索引鍵和標籤篩選條件,選擇組成快照集的索引鍵/值。 建立快照集之後,其中的索引鍵/值一定會維持不變。

您可以在 SnapshotName 結構中設定 Selector 欄位,以從快照集載入索引鍵-值:

options := &azureappconfiguration.Options{
	Selectors: []azureappconfiguration.Selector{
		{KeyFilter: "app*", LabelFilter: "prod"},
		{SnapshotName: "my-snapshot"},
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

快照參考

快照參考是參考相同應用程式組態存放區中快照的組態設定。 載入時,提供者會解析它,並新增該快照集中的所有索引鍵/值。 使用快照參考可以在執行時切換快照,與新增快照選擇器不同,後者需要修改程式碼和/或重新啟動才能切換到新的快照。

欲了解更多關於建立快照參考的資訊,請參考 快照參考概念。

備註

若要使用快照參考,請使用 1.6.0 或更新版本的 azureappconfiguration。

地理複製

如需使用異地複寫的相關資訊,請移至啟用異地復寫。

啟動重試

組態載入是應用程式啟動期間的重要路徑作業。 為了確保可靠性,Azure 應用程式組態提供者會在初始設定負載期間實作強固的重試機制。 這有助於保護您的應用程式免於暫時性網路問題,否則可能會防止成功啟動。

您可以透過 Options.StartupOptions自訂此行為:

options := &azureappconfiguration.Options{
	StartupOptions: azureappconfiguration.StartupOptions{
		Timeout: 5 * time.Minute,
	},
}

appConfig, err := azureappconfiguration.Load(ctx, authOptions, options)

後續步驟

若要了解如何使用 Go 組態提供者,請繼續進行下列教學課程。