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

创建 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>
    

连接到应用程序配置存储区

现在,你将使用从 Azure 应用配置加载其配置的 Gin 框架创建 Go Web 应用程序。

使用 Gin 创建 Web 应用程序

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

package main

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

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

// Config defines the application configuration structure
type Config struct {
	App     App
	Message string
}

// App contains application-specific configuration
type App struct {
	Name      string
	DebugMode bool
}

// loadConfiguration handles loading the configuration from Azure App Configuration
func loadConfiguration() (Config, error) {
	// Get 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
	authOptions := azureappconfiguration.AuthenticationOptions{
		Endpoint:   endpoint,
		Credential: credential,
	}

	// Configuration setup
	options := &azureappconfiguration.Options{
		Selectors: []azureappconfiguration.Selector{
			{
				KeyFilter:   "Config.*",
				LabelFilter: "",
			},
		},
		// Remove the prefix when mapping to struct fields
		TrimKeyPrefixes: []string{"Config."},
	}

	// Create configuration provider with timeout
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	appCfgProvider, err := azureappconfiguration.Load(ctx, authOptions, options)
	if err != nil {
		return Config{}, err
	}

	// Parse configuration into struct
	var config Config
	err = appCfgProvider.Unmarshal(&config, nil)
	if err != nil {
		return Config{}, err
	}

	return config, nil
}

func main() {
	// Load configuration
	config, err := loadConfiguration()
	if err != nil {
		log.Fatalf("Error loading configuration: %v", err)
	}

	// Configure Gin based on app settings
	if config.App.DebugMode {
		// Set Gin to debug mode for development
		gin.SetMode(gin.DebugMode)
		log.Println("Running in DEBUG mode")
	} else {
		// Set Gin to release mode for production
		gin.SetMode(gin.ReleaseMode)
		log.Println("Running in RELEASE mode")
	}

	// 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,
		})
	})

	// Start the server on port 8080
	log.Printf("Starting %s on http://localhost:8080", config.App.Name)
	if err := r.Run(":8080"); 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 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 页面如下所示:

    浏览器的屏幕截图。在本地启动 Quickstart 应用程序。

清理资源

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。

重要

删除资源组的操作不可逆。 将永久删除资源组以及其中的所有资源。 请确保不要意外删除错误的资源组或资源。 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。

  1. 登录到 Azure 门户,然后选择“资源组”。
  2. 按名称筛选框中,输入资源组的名称。
  3. 在结果列表中,选择资源组名称以查看概述。
  4. 选择“删除资源组”。
  5. 系统会要求确认是否删除资源组。 重新键入资源组的名称进行确认,然后选择“删除”。

片刻之后,将会删除该资源组及其所有资源。

后续步骤

在本快速入门中,你已使用 Azure 应用配置创建了 Go Web 应用程序。 你已了解如何执行以下操作:

  • 在 Web 应用程序中从 Azure 应用程序配置加载配置
  • 将强类型配置与 Unmarshal 配合使用
  • 根据集中存储的设置配置 Web 应用程序

若要详细了解 Azure 应用配置 Go 提供程序,请参阅 参考文档