快速入门:使用 Azure 应用配置创建 Go 控制台应用

在本快速入门中,你将使用 Azure 应用配置通过 Azure 应用配置 Go 提供程序客户端库集中存储和管理应用程序设置。

适用于 Go 的应用配置提供程序简化了将键值从 Azure 应用配置应用到 Go 应用程序的努力。 它支持将设置绑定到 Go 结构。 它提供了从多个标签中组合配置、去除密钥前缀、自动解析 Key Vault 引用等功能,以及更多其他功能。

先决条件

添加键值

将以下键值添加到应用程序配置存储区。 有关如何使用 Azure 门户或 CLI 将键值添加到存储区的详细信息,请转到创建键值

密钥 价值 内容类型
Config.Message 世界您好! 留空
Config.App.Name Go 控制台应用 留空
Config.App.Debug true 留空
Config.App.Settings {“timeout”: 30, “retryCount”: 3} application/json

创建 Go 控制台应用

  1. 为项目创建新目录。

    mkdir app-configuration-quickstart
    cd app-configuration-quickstart
    
  2. 初始化新的 Go 模块。

    go mod init app-configuration-quickstart
    
  3. 将 Azure 应用配置提供程序添加为依赖项。

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

连接到应用程序配置存储区

以下示例演示如何从 Azure 应用配置检索配置数据。 可以使用 Microsoft Entra ID(建议)或连接字符串连接到应用程序配置存储区。

示例 1:将键值取消封送到目标配置结构

在此示例中,使用 Unmarshal 该方法将配置值加载到强类型结构中。 这提供了一种类型安全的方法来访问配置。

创建包含以下内容的文件 unmarshal_sample.go

package main

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

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

// Configuration structure that matches your key-values in App Configuration
type Config struct {
	Message string
	App     struct {
		Name     string
		Debug    bool
		Settings struct {
			Timeout     int
			RetryCount  int
		}
	}
}

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

	// Get the endpoint from environment variable
	endpoint := os.Getenv("AZURE_APPCONFIG_ENDPOINT")
	if endpoint == "" {
		log.Fatal("AZURE_APPCONFIG_ENDPOINT environment variable is not set")
	}

	// 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 with endpoint and credential
	authOptions := azureappconfiguration.AuthenticationOptions{
		Endpoint:   endpoint,
		Credential: credential,
	}

	// Configure which keys to load and trimming options
	options := &azureappconfiguration.Options{
		Selectors: []azureappconfiguration.Selector{
			{
				KeyFilter:   "Config.*",
				LabelFilter: "",
			},
		},
		TrimKeyPrefixes: []string{"Config."},
	}

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

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

	// Create a configuration object and unmarshal the loaded key-values into it
	var config Config
	if err := provider.Unmarshal(&config, nil); err != nil {
		log.Fatalf("Failed to unmarshal configuration: %v", err)
	}

	// Display the configuration values
	fmt.Println("\nConfiguration Values:")
	fmt.Println("---------------------")
	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)
	fmt.Printf("Retry Count: %d\n", config.App.Settings.RetryCount)
}

示例 2:将键值作为已经构造好的 JSON 字节获取。

在此示例中,你将使用 GetBytes 该方法以 JSON 字节的形式检索配置。 此方法非常适合与使用内置库 encoding/json 或第三方包(例如 viper)的现有代码集成。

创建包含以下内容的文件 getbytes_sample.go

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

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

// Configuration structure that matches your key-values in App Configuration
type Config struct {
	Message string `json:"Message"`
	App     struct {
		Name     string `json:"Name"`
		Debug    bool   `json:"Debug"`
		Settings struct {
			Timeout    int `json:"timeout"`
			RetryCount int `json:"retryCount"`
		} `json:"Settings"`
	} `json:"App"`
}

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

	// Get the endpoint from environment variable
	endpoint := os.Getenv("AZURE_APPCONFIG_ENDPOINT")
	if endpoint == "" {
		log.Fatal("AZURE_APPCONFIG_ENDPOINT environment variable is not set")
	}

	// 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 with endpoint and credential
	authOptions := azureappconfiguration.AuthenticationOptions{
		Endpoint:   endpoint,
		Credential: credential,
	}

	// Configure which keys to load and trimming options
	options := &azureappconfiguration.Options{
		Selectors: []azureappconfiguration.Selector{
			{
				KeyFilter:   "Config.*",
				LabelFilter: "",
			},
		},
		TrimKeyPrefixes: []string{"Config."},
	}

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

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

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

	fmt.Println("\nRaw JSON Configuration:")
	fmt.Println("------------------------")
	fmt.Println(string(jsonBytes))

	// Integration with other libraries
	// Using with standard library json.Unmarshal:
	// 	json.Unmarshal(jsonBytes, &config)
	//
	// Using with viper:
	// 	viper.ReadConfig(bytes.NewBuffer(jsonBytes))
}

运行应用程序

  1. 设置用于身份验证的环境变量。

    将名为 AZURE_APPCONFIG_ENDPOINT 的环境变量设置为 Azure 门户中应用商店的“概述”下找到的应用程序配置存储区的终结点

    如果使用 Windows 命令提示符,则请运行以下命令并重启命令提示符,这样更改才会生效:

    setx AZURE_APPCONFIG_ENDPOINT "<endpoint-of-your-app-configuration-store>"
    

    如果使用 PowerShell,请运行以下命令:

    $Env:AZURE_APPCONFIG_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
    

    如果使用 macOS 或 Linux,则请运行以下命令:

    export AZURE_APPCONFIG_ENDPOINT='<endpoint-of-your-app-configuration-store>'
    

    此外,请确保已使用 Azure CLI 登录,或使用环境变量进行 Azure 身份验证:

    az login
    
  2. 正确设置环境变量后,运行以下命令以运行 Unmarshal 示例:

    go run unmarshal_sample.go
    

    应该会看到与下面类似的输出:

    Azure App Configuration - Go Provider Example
    ---------------------------------------------
    Loading configuration from Azure App Configuration...
    
    Configuration Values:
    ---------------------
    Message: Hello World!
    App Name: Go Console App
    Debug Mode: true
    Timeout: 30 seconds
    Retry Count: 3
    
  3. 运行 GetBytes 示例:

    go run getbytes_sample.go
    

    应该会看到与下面类似的输出:

    Azure App Configuration - GetBytes Example
    ------------------------------------------
    Loading configuration from Azure App Configuration...
    
    Raw JSON Configuration:
    ------------------------
    {"App":{"Debug":true,"Name":"Go Console App","Settings":{"retryCount":3,"timeout":30}},"Message":"Hello World!"}
    

清理资源

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。

重要

删除资源组的操作不可逆。 将永久删除资源组以及其中的所有资源。 请确保不要意外删除错误的资源组或资源。 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。

  1. 登录到 Azure 门户,然后选择“资源组”。
  2. 按名称筛选框中,输入资源组的名称。
  3. 在结果列表中,选择资源组名称以查看概述。
  4. 选择“删除资源组”。
  5. 系统会要求确认是否删除资源组。 重新键入资源组的名称进行确认,然后选择“删除”。

片刻之后,将会删除该资源组及其所有资源。

后续步骤

在本快速入门中,你创建了一个新的应用程序配置存储区,并了解了如何在控制台应用程序中使用 Azure 应用配置 Go 提供程序访问键值。

若要详细了解 Azure 应用配置 Go 提供程序,请参阅 参考文档