このクイックスタートでは、Azure App Configuration を使用して、 Azure App Configuration Go プロバイダー クライアント ライブラリを使用して、アプリケーション設定のストレージと管理を一元化します。
Go 用 App Configuration プロバイダーは、Azure App Configuration から Go アプリケーションにキー値を適用する作業を簡略化します。 これにより、Go 構造体へのバインド設定が有効になります。 複数のラベルからの構成合成、キー プレフィックスのトリミング、Key Vault 参照の自動解決などの機能が提供されます。
[前提条件]
- アクティブなサブスクリプションを持つ Azure アカウント。 無料で作成できます。
- アプリ設定ストア。 ストアを作成する。
- Go (1.18 以降)。 Go をインストールします。
キーバリューを追加する
App Configuration ストアに次のキーと値を追加します。 Azure portal または CLI を使用してストアにキーと値を追加する方法の詳細については、キーと値の作成に関する記事を参照してください。
鍵 | 価値 | コンテンツの種類 |
---|---|---|
Config.Message | ハローワールド! | 空のままにします |
Config.App.Name | Go コンソール アプリ | 空のままにします |
Config.App.Debug | 真実 | 空のままにします |
Config.App.Settings | {"timeout": 30, "retryCount": 3} | アプリケーション /json |
App Configuration に接続する
プロジェクトの新しいディレクトリを作成します。
mkdir app-configuration-quickstart cd app-configuration-quickstart
新しい Go モジュールを初期化します。
go mod init app-configuration-quickstart
依存関係として Azure App Configuration プロバイダーを追加します。
go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
次の内容を含む
appconfig.go
という名前のファイルを作成します。 Microsoft Entra ID (推奨) または接続文字列を使用して App Configuration ストアに接続できます。
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 データとして取得し、構造体バインディングに代わる柔軟な代替手段を提供します。 このアプローチは、標準の encoding/json
パッケージや viper
などの構成フレームワークなどの既存の JSON 処理ライブラリとシームレスに統合されます。 動的構成を使用する場合、構成を一時的に格納する必要がある場合、または JSON 入力を必要とする既存のシステムと統合する場合に特に便利です。 GetBytes を使用すると、Azure App Configuration の集中管理機能の恩恵を受けながら、ユニバーサル互換形式で構成に直接アクセスできます。
次の内容を含む 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
// ...
}
アプリケーションを実行する
認証用の環境変数を設定します。
AZURE_APPCONFIG_ENDPOINTという名前の環境変数を、Azure portal のストアの概要にある App Configuration ストアのエンドポイントに設定します。
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
環境変数が正しく設定されたら、次のコマンドを実行して 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
GetBytes の例を実行します。
go run getbytes_sample.go
次のような出力が表示されます。
Raw JSON Configuration: ------------------------ {"App":{"Debug":true,"Name":"Go Console App","Settings":{"retryCount":3,"timeout":30}},"Message":"Hello World!"}
リソースをクリーンアップする
この記事で作成したリソースを継続して使用しない場合は、ここで作成したリソース グループを削除して課金されないようにしてください。
Von Bedeutung
リソース グループを削除すると、元に戻すことができません。 リソース グループとそのすべてのリソースは完全に削除されます。 間違ったリソース グループやリソースをうっかり削除しないようにしてください。 この記事のリソースを、保持したい他のリソースを含むリソース グループ内に作成した場合は、リソース グループを削除する代わりに、各リソースをそれぞれのペインから個別に削除します。
- Azure portal にサインインし、 [リソース グループ] を選択します。
- [名前でフィルター] ボックスにリソース グループの名前を入力します。
- 結果一覧でリソース グループ名を選択し、概要を表示します。
- [リソース グループの削除] を選択します。
- リソース グループの削除の確認を求めるメッセージが表示されます。 確認のためにリソース グループの名前を入力し、 [削除] を選択します。
しばらくすると、リソース グループとそのすべてのリソースが削除されます。
次のステップ
このクイック スタートでは、新しい App Configuration ストアを作成し、コンソール アプリケーションで Azure App Configuration Go プロバイダーを使用してキー値にアクセスする方法について説明しました。
Azure App Configuration Go プロバイダーの詳細については、 リファレンス ドキュメントを参照してください。