共用方式為


快速入門:使用 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"
     	"log"
     	"os"
    
     	"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

方法 Unmarshal 提供型別安全的方式,將組態值載入 Go 結構。 此方法可防止在組態鍵值中錯誤鍵入導致的運行時錯誤,並使您的程式碼更容易維護。 Unmarshal 對於具有巢狀結構、不同數據類型的複雜組態,或在跨元件使用需要清楚設定合約的微服務時,特別有價值。

使用下列內容建立名為 main.go 的檔案:

package main

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

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 應用程式設定的集中式管理功能。

使用下列內容更新 main.go

	// Existing code in main.go
	// ... ...
	fmt.Printf("Timeout: %d seconds\n", config.App.Settings.Timeout)
	fmt.Printf("Retry Count: %d\n", config.App.Settings.RetryCount)

	// 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. 正確設定環境變數之後,請執行下列命令來執行 UnmarshalGetBytes 範例:

    go mod tidy
    go run .
    

    您應該會看到如下輸出:

    Configuration Values:
    ---------------------
    Message: Hello World!
    App Name: Go Console App
    Debug Mode: true
    Timeout: 30 seconds
    Retry Count: 3
    
    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 提供者,請參閱 參考檔