共用方式為


快速入門:使用 Azure 應用程式組態建立 Go Web 應用程式

在本快速入門中,您會使用 Azure 應用程式組態,使用 Gin 架構Azure 應用程式組態 Go 提供者來集中儲存和管理 Go Web 應用程式的應用程式設定。

適用於 Go 的應用程式設定提供者可簡化將索引鍵/ 值從 Azure 應用程式組態套用至 Go 應用程式的工作。 它能將設定繫結至 Go 結構體。 它提供多個標籤的設定組合、索引鍵前置詞修剪、Key Vault 參考的自動解析等功能。

先決條件

新增索引鍵/值

將下列索引鍵/值新增至應用程式組態存放區,並保留標籤內容類型的預設值。 若要瞭解如何使用 Azure 入口網站或 CLI 將鍵值新增至儲存區的詳細資訊,請移至建立鍵值

鑰匙 價值觀
Config.Message 來自 Azure 應用程式組態的問候
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>
    

連線至應用程式組態存放區

建立名為 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
}

使用 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 入口網站中,於市集的 總覽 底下找到的應用程式組態存放區端點。

    如果您使用 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 mod tidy
    go run .
    

    您應該會看到如下所示的輸出:

    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。 網頁如下所示:

    瀏覽器的螢幕快照。在本機啟動快速入門應用程式。

清理資源

如果您不想繼續使用本文中建立的資源,請刪除在此處建立的資源群組,以避免產生費用。

這很重要

刪除資源群組是無法回復的動作。 資源群組和其中的所有資源都將被永久刪除。 請確定您不會誤刪錯誤的資源群組或資源。 如果您是在包含其他您想保留資源的資源群組中建立本文的資源,則應該從各自的面板中逐一刪除每個資源,而不用刪除整個資源群組。

  1. 登入 Azure 入口網站,然後選取 [資源群組]
  2. 在 [依名稱篩選] 方塊中,輸入您資源群組的名稱。
  3. 在結果清單中,選取資源群組名稱以查看概觀。
  4. 選擇 ,刪除資源群組
  5. 系統將會要求您確認是否刪除資源群組。 輸入您資源群組的名稱以進行確認,然後選取 [刪除]

不久後,系統便會刪除該資源群組及其所有的資源。

後續步驟

在本快速入門中,您已使用 Azure 應用程式組態建立 Go Web 應用程式。 您已學到如何做到以下幾點:

  • 在 Web 應用程式中載入來自 Azure App Configuration 的組態設定
  • 搭配 Unmarshal 使用強型別組態
  • 根據集中儲存的設定來設定 Web 應用程式

若要深入瞭解 Azure 應用程式設定 Go 提供者,請參閱 參考檔