다음을 통해 공유


빠른 시작: Azure App Configuration을 사용하여 Go 웹앱 만들기

이 빠른 시작에서는 Azure App Configuration을 사용하여 Gin 프레임워크 및 Azure App Configuration Go 공급자를 사용하여 Go 웹 애플리케이션에 대한 애플리케이션 설정의 스토리지 및 관리를 중앙 집중화합니다.

Go용 App Configuration 공급자는 Azure App Configuration에서 Go 애플리케이션에 키-값을 적용하는 작업을 간소화합니다. Go 구조체에 대한 바인딩 설정을 사용하도록 설정합니다. 여러 레이블의 구성 컴퍼지션, 키 접두사 트리밍, Key Vault 참조의 자동 확인 등과 같은 기능을 제공합니다.

필수 조건

키-값 추가

App Configuration 저장소에 다음 키-값을 추가하고 레이블콘텐츠 형식은 기본값으로 둡니다. Azure Portal 또는 CLI를 사용하여 저장소에 키-값을 추가하는 방법에 대한 자세한 내용은 키-값 만들기로 이동합니다.

열쇠 가치
설정.메시지 안녕하세요, Azure App Configuration에서
설정.앱.이름 진 샘플 앱
Config.App.Port 8080

Go 웹 애플리케이션 만들기

  1. 웹 애플리케이션에 대한 새 디렉터리를 만듭니다.

    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을 사용하여 웹 애플리케이션 만들기

다음 내용으로 명명된 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)
	}
}

웹 애플리케이션 실행

  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. 웹 브라우저를 열고 http://localhost:8080로 이동합니다. 웹 페이지는 다음과 같습니다.

    브라우저의 스크린샷. 로컬에서 빠른 시작 앱을 시작합니다.

자원을 정리하세요

이 문서에서 만든 리소스를 계속 사용하지 않으려면 여기서 만든 리소스 그룹을 삭제하여 요금이 부과되지 않도록 합니다.

중요합니다

리소스 그룹을 삭제하면 다시 되돌릴 수 없습니다. 리소스 그룹 및 포함된 모든 리소스가 영구적으로 삭제됩니다. 잘못된 리소스 그룹 또는 리소스를 자동으로 삭제하지 않도록 합니다. 유지하려는 다른 리소스가 포함된 리소스 그룹 내에서 이 문서에 대한 리소스를 만든 경우 리소스 그룹을 삭제하는 대신 해당 창에서 각 리소스를 개별적으로 삭제합니다.

  1. Azure Portal에 로그인하고 리소스 그룹을 선택합니다.
  2. 이름으로 필터링 상자에서 리소스 그룹의 이름을 입력합니다.
  3. 결과 목록에서 리소스 그룹 이름을 선택하여 개요를 확인합니다.
  4. 리소스 그룹 삭제를 선택합니다.
  5. 리소스 그룹 삭제를 확인하는 메시지가 표시됩니다. 리소스 그룹의 이름을 입력하여 확인하고 삭제를 선택합니다.

잠시 후, 리소스 그룹 및 모든 해당 리소스가 삭제됩니다.

다음 단계

이 빠른 시작에서는 Azure App Configuration을 사용하여 Go 웹 애플리케이션을 만들었습니다. 당신은 다음을 배우셨습니다:

  • 웹 애플리케이션에서 Azure App Configuration의 구성을 로드하기
  • Unmarshal에서 강력한 형식의 구성 사용
  • 중앙 집중식으로 저장된 설정에 따라 웹 애플리케이션 구성

Azure App Configuration Go 공급자에 대한 자세한 내용은 참조 문서를 참조하세요.