次の方法で共有


クイック スタート: Azure App Configuration を使用して Go Web アプリを作成する

このクイック スタートでは、Azure App Configuration を使用して、 Gin フレームワークAzure App Configuration Go プロバイダーを使用して、Go Web アプリケーションのアプリケーション設定のストレージと管理を一元化します。

Go 用 App Configuration プロバイダーは、Azure App Configuration から Go アプリケーションにキー値を適用する作業を簡略化します。 これにより、Go 構造体へのバインド設定が有効になります。 複数のラベルからの構成合成、キー プレフィックスのトリミング、Key Vault 参照の自動解決などの機能が提供されます。

[前提条件]

キーバリューを追加する

App Configuration ストアに次のキーと値を追加し、[ラベル][コンテンツのタイプ] を既定値のままにします。 Azure portal または CLI を使用してストアにキーと値を追加する方法の詳細については、キーと値の作成に関する記事を参照してください。

価値
Config.Message Azure App Configurationからこんにちは
Config.App.Name Gin サンプル アプリ
Config.App.Port 8080

Go Web アプリケーションを作成する

  1. Web アプリケーション用の新しいディレクトリを作成します。

    mkdir app-configuration-web
    cd app-configuration-web
    
  2. 新しい Go モジュールを初期化します。

    go mod init app-configuration-web
    
  3. 必要な依存関係を追加します。

    go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
    go get github.com/gin-gonic/gin
    
  4. HTML テンプレートのテンプレート ディレクトリを作成します。

    mkdir templates
    
  5. ホーム ページの HTML テンプレートを作成します。 templates/index.html に次の内容を追加します。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{.Title}}</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #f5f5f5;
            }
            .container {
                margin: 50px auto;
                max-width: 800px;
                text-align: center;
                background-color: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            h1 {
                color: #333;
            }
            p {
                color: #666;
                font-size: 18px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>{{.Message}}</h1>
            <p>{{.App}}</p>
        </div>
    </body>
    </html>
    

App Configuration ストアに接続する

次の内容を含む 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
}

Gin を使用して Web アプリケーションを作成する

次の内容を含む main.go という名前のファイルを作成します。

package main

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

	"github.com/gin-gonic/gin"
)

type Config struct {
	App     App
	Message string
}

type App struct {
	Name      string
	Port      int
}

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

	// Load configuration from Azure App Configuration
	provider, err := loadAzureAppConfiguration(ctx)
	if err != nil {
		log.Fatalf("Error loading configuration: %v", err)
	}

	// Unmarshal the configuration into the application-specific struct
	var config Config
	if err := provider.Unmarshal(&config, nil); err != nil {
		log.Fatalf("Failed to unmarshal configuration: %v", err)
	}

	// Initialize Gin router
	r := gin.Default()

	// Load HTML templates
	r.LoadHTMLGlob("templates/*")

	// Define a route for the homepage
	r.GET("/", func(c *gin.Context) {
		c.HTML(200, "index.html", gin.H{
			"Title":   "Home",
			"Message": config.Message,
			"App":     config.App.Name,
		})
	})

	// Use the port from configuration
	portStr:= fmt.Sprintf(":%d", config.App.Port)
	
	// Start the server on configured port
	log.Printf("Starting %s on http://localhost%s", config.App.Name, portStr)
	if err := r.Run(portStr); err != nil {
		log.Fatalf("Error starting server: %v", err)
	}
}

Web アプリケーションの実行

  1. 認証用の環境変数を設定します。

    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
    
  2. アプリケーションを実行します。

    go run main.go
    

    次のような出力が表示されます。

    Running in DEBUG mode
    Starting Gin Web App on http://localhost:8080
    [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
    [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
    - using env:	export GIN_MODE=release
    - using code:	gin.SetMode(gin.ReleaseMode)
    [GIN-debug] Loading templates from ./templates/*
    [GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
    [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
    Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
    [GIN-debug] Listening and serving HTTP on :8080
    
  3. Web ブラウザーを開き、http://localhost:8080に移動します。 Web ページは次のようになります。

    ブラウザーのスクリーンショット。クイック スタート アプリをローカルで起動する。

リソースをクリーンアップする

この記事で作成したリソースを継続して使用しない場合は、ここで作成したリソース グループを削除して課金されないようにしてください。

Von Bedeutung

リソース グループを削除すると、元に戻すことができません。 リソース グループとそのすべてのリソースは完全に削除されます。 間違ったリソース グループやリソースをうっかり削除しないようにしてください。 この記事のリソースを、保持したい他のリソースを含むリソース グループ内に作成した場合は、リソース グループを削除する代わりに、各リソースをそれぞれのペインから個別に削除します。

  1. Azure portal にサインインし、 [リソース グループ] を選択します。
  2. [名前でフィルター] ボックスにリソース グループの名前を入力します。
  3. 結果一覧でリソース グループ名を選択し、概要を表示します。
  4. [リソース グループの削除] を選択します。
  5. リソース グループの削除の確認を求めるメッセージが表示されます。 確認のためにリソース グループの名前を入力し、 [削除] を選択します。

しばらくすると、リソース グループとそのすべてのリソースが削除されます。

次のステップ

このクイック スタートでは、Azure App Configuration を使用して Go Web アプリケーションを作成しました。 以下の方法を学習しました。

  • Web アプリケーションで Azure App Configuration から構成を読み込む
  • Unmarshal で厳密に型指定された構成を使用する
  • 一元的に保存された設定に基づいて Web アプリケーションを構成する

Azure App Configuration Go プロバイダーの詳細については、 リファレンス ドキュメントを参照してください