다음을 통해 공유


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

이 빠른 시작에서는 Azure App Configuration을 사용하여 Azure App Configuration Go 공급자 클라이언트 라이브러리를 사용하여 애플리케이션 설정의 스토리지 및 관리를 중앙 집중화합니다.

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

필수 조건

키-값 추가

App Configuration 저장소에 다음 키-값을 추가합니다. Azure Portal 또는 CLI를 사용하여 저장소에 키-값을 추가하는 방법에 대한 자세한 내용은 키-값 만들기로 이동합니다.

열쇠 가치 콘텐츠 형식
Config.Message 전 세계 여러분 안녕하세요! 비워둠
Config.App.Name Go 콘솔 앱 비워둠
Config.App.Debug true 비워둠
Config.App.Settings {"timeout": 30, "retryCount": 3} application/json

App Configuration에 연결

  1. 프로젝트에 대한 새 디렉터리를 만듭니다.

    mkdir app-configuration-quickstart
    cd app-configuration-quickstart
    
  2. 새 Go 모듈을 초기화합니다.

    go mod init app-configuration-quickstart
    
  3. Azure App Configuration 공급자를 종속성으로 추가합니다.

    go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
    
  4. 다음과 같은 내용으로 appconfig.go라는 파일을 만듭니다. Microsoft Entra ID(권장) 또는 연결 문자열을 사용하여 App Configuration 저장소에 연결할 수 있습니다.

     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
     }
    

언마샬

이 메서드는 Unmarshal Go 구조체에 구성 값을 로드하는 형식 안전 방법을 제공합니다. 이 방법을 사용하면 런타임 오류가 잘못 입력된 구성 키를 방지하고 코드를 더 쉽게 유지 관리할 수 있습니다. Unmarshal 은 중첩된 구조, 다른 데이터 형식을 사용하는 복잡한 구성 또는 구성 요소 간에 명확한 구성 계약이 필요한 마이크로 서비스를 사용하는 경우 특히 유용합니다.

다음 내용으로 명명된 main.go 파일을 만듭니다.

package main

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

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 패키지 또는 구성 프레임워크와 같은 기존 JSON 처리 라이브러리와 원활하게 통합됩니다 viper. 동적 구성으로 작업하거나, 구성을 일시적으로 저장해야 하거나, JSON 입력이 필요한 기존 시스템과 통합할 때 특히 유용합니다. GetBytes를 사용하면 Azure App Configuration의 중앙 집중식 관리 기능을 활용하면서 보편적으로 호환되는 형식으로 구성에 직접 액세스할 수 있습니다.

main.go를 다음 내용으로 업데이트합니다.

	// Existing code in main.go
	// ... ...
	fmt.Printf("Timeout: %d seconds\n", config.App.Settings.Timeout)
	fmt.Printf("Retry Count: %d\n", config.App.Settings.RetryCount)

	// 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
	// ...

애플리케이션 실행

  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. 환경 변수가 제대로 설정되면 다음 명령을 실행하여 UnmarshalGetBytes 예제를 실행합니다.

    go mod tidy
    go run .
    

    다음과 비슷한 결과가 나타나야 합니다.

    Configuration Values:
    ---------------------
    Message: Hello World!
    App Name: Go Console App
    Debug Mode: true
    Timeout: 30 seconds
    Retry Count: 3
    
    Raw JSON Configuration:
    ------------------------
    {"App":{"Debug":true,"Name":"Go Console App","Settings":{"retryCount":3,"timeout":30}},"Message":"Hello World!"}
    

자원을 정리하세요

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

중요합니다

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

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

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

다음 단계

이 빠른 시작에서는 새 App Configuration 저장소를 만들고 콘솔 애플리케이션에서 Azure App Configuration Go 공급자를 사용하여 키-값에 액세스하는 방법을 알아보았습니다.

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