你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 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

连接到应用程序配置

  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
    
  4. 创建包含以下内容的名为 appconfig.go 的文件。 可以使用 Microsoft Entra ID(建议)或连接字符串连接到应用程序配置存储区。

package main

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

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

func loadAzureAppConfiguration(ctx context.Context) (*azureappconfiguration.Azureappconfiguration, error) {
	// 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."},
	}

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

	return appConfig, nil
}

取消封送

该方法 Unmarshal 提供了一种类型安全的方法来将配置值加载到 Go 结构中。 此方法可防止运行时错误键入的配置密钥,并使代码更易于维护。 Unmarshal 对于具有嵌套结构、不同数据类型的复杂配置,或者在跨组件使用需要明确配置协定的微服务时,尤其有用。

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

package main

import (
	"context"
	"fmt"
	"log"
	"time"
)

// 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() {
	// Create a context with timeout
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Load configuration
	provider, err := loadAzureAppConfiguration(ctx)
	if err != nil {
		log.Fatalf("Error loading 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)
}

JSON 字节

该方法 GetBytes 以原始 JSON 数据形式检索您的配置,提供一种灵活的替代结构绑定的方法。 此方法能够与现有的 JSON 处理库(如标准 encoding/json 包)无缝集成,以及配置框架如 viper。 在使用动态配置、需要临时存储配置或与需要 JSON 输入的现有系统集成时,它特别有用。 使用 GetBytes 可让你以通用兼容格式直接访问配置,同时仍受益于 Azure 应用配置的集中式管理功能。

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

package main

import (
	"context"
	"fmt"
	"log"
	"time"
	
	"github.com/spf13/viper"
)

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

	// Load configuration using the common function
	provider, err := loadAzureAppConfiguration(ctx)
	if err != nil {
		log.Fatalf("Error loading 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))
	
	// Initialize a new Viper instance
	v := viper.New()
	v.SetConfigType("json") // Set the config format to JSON
	
	// Load the JSON bytes into Viper
	if err := v.ReadConfig(bytes.NewBuffer(jsonBytes)); err != nil {
		log.Fatalf("Failed to read config into viper: %v", err)
	}

	// Use viper to access your configuration
	// ...
}

运行应用程序

  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
    

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

    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
    

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

    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 提供程序,请参阅 参考文档