Firestore로 세션 처리

이 튜토리얼에서는 Cloud Run에서 세션을 처리하는 방법을 보여줍니다.

대부분의 앱은 인증 및 사용자 환경설정에 대한 세션 처리가 필요합니다. Gorilla 웹 도구 sessions 패키지에는 이 함수를 수행하기 위해 파일 시스템 기반 구현이 함께 제공됩니다. 하지만 한 인스턴스에 기록된 세션이 다른 인스턴스와 다를 수 있으므로 여러 인스턴스에서 제공될 수 있는 앱에는 이 구현이 적절하지 않습니다. gorilla/sessions 패키지에는 쿠키 기반 구현도 함께 제공됩니다. 그러나 이를 구현하기 위해 쿠키를 암호화하고 클라이언트에 세션 ID 뿐만 아니라 전체 세션을 저장해야 하며, 일부 앱에 비해 너무 큰 경우가 있습니다.

목표

  • 앱을 작성합니다.
  • 로컬에서 앱을 실행합니다.
  • Cloud Run에 앱을 배포합니다.

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소( )를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

시작하기 전에

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Firestore API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Firestore API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. Google Cloud 콘솔의 Cloud Shell에서 앱을 엽니다.

    Cloud Shell로 이동

    Cloud Shell을 사용하면 브라우저에서 직접 명령줄을 통해 클라우드 리소스에 액세스할 수 있습니다. 브라우저에서 Cloud Shell을 열고 계속을 클릭하여 샘플 코드를 다운로드하고 앱 디렉터리로 변경합니다.

  9. Cloud Shell에서 새 Google Cloud 프로젝트를 사용하도록 gcloud CLI를 구성합니다.
    # Configure gcloud for your project
    gcloud config set project YOUR_PROJECT_ID
    

프로젝트 설정

  1. 터미널 창에서 샘플 앱 저장소를 로컬 머신에 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git
  2. 샘플 코드가 있는 디렉터리로 변경합니다.

    cd golang-samples/getting-started/sessions

웹 앱 이해하기

이 앱은 모든 사용자에게 다양한 언어로 인사말을 표시합니다. 재사용자에게는 항상 같은 언어로 인사말을 표시합니다.

다양한 언어로 인사말을 표시하는 여러 개의 앱 창

앱에서 사용자 환경설정을 저장하려면 세션에서 현재 사용자에 대한 정보를 저장할 수 있는 방법이 필요합니다. 이 샘플 앱은 Firestore를 사용하여 세션 데이터를 저장합니다.

  1. 앱은 종속 항목을 가져오고 sessions.Store 및 HTML 템플릿을 저장할 app 유형을 정의하고 인사말 목록을 정의하면서 시작합니다.

    import (
    	"context"
    	"html/template"
    	"log"
    	"math/rand"
    	"net/http"
    	"os"
    
    	"cloud.google.com/go/firestore"
    )
    
    // app stores a sessions.Store. Create a new app with newApp.
    type app struct {
    	tmpl         *template.Template
    	collectionID string
    	projectID    string
    }
    
    // session stores the client's session information.
    // This type is also used for executing the template.
    type session struct {
    	Greetings string `json:"greeting"`
    	Views     int    `json:"views"`
    }
    
    // greetings are the random greetings that will be assigned to sessions.
    var greetings = []string{
    	"Hello World",
    	"Hallo Welt",
    	"Ciao Mondo",
    	"Salut le Monde",
    	"Hola Mundo",
    }
    
  2. 그런 후 앱은 새 app 인스턴스를 만드는 main 함수를 정의하고 색인 핸들러를 등록하고 HTTP 서버를 시작합니다. newApp 함수는 projectIDcollectionID 값을 설정하여 app 인스턴스를 만들고 HTML 템플릿을 파싱합니다.

    func main() {
    	port := os.Getenv("PORT")
    	if port == "" {
    		port = "8080"
    	}
    
    	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
    	if projectID == "" {
    		log.Fatal("GOOGLE_CLOUD_PROJECT must be set")
    	}
    
    	// collectionID is a non-empty identifier for this app, it is used as the Firestore
    	// collection name that stores the sessions.
    	//
    	// Set it to something more descriptive for your app.
    	collectionID := "hello-views"
    
    	a, err := newApp(projectID, collectionID)
    	if err != nil {
    		log.Fatalf("newApp: %v", err)
    	}
    
    	http.HandleFunc("/", a.index)
    
    	log.Printf("Listening on port %s", port)
    	if err := http.ListenAndServe(":"+port, nil); err != nil {
    		log.Fatal(err)
    	}
    }
    
    // newApp creates a new app.
    func newApp(projectID, collectionID string) (app, error) {
    	tmpl, err := template.New("Index").Parse(`<body>{{.Views}} {{if eq .Views 1}}view{{else}}views{{end}} for "{{.Greetings}}"</body>`)
    	if err != nil {
    		log.Fatalf("template.New: %v", err)
    	}
    
    	return app{
    		tmpl:         tmpl,
    		collectionID: collectionID,
    		projectID:    projectID,
    	}, nil
    }
    
  3. 색인 핸들러는 사용자의 세션을 가져오며, 필요한 경우 세션을 생성합니다. 새 세션에는 임의의 언어와 조회수 0이 할당됩니다. 그런 다음 조회수가 1씩 증가하고 세션이 저장되며 HTML 템플릿이 응답을 작성합니다.

    
    // index uses sessions to assign users a random greeting and keep track of
    // views.
    func (a *app) index(w http.ResponseWriter, r *http.Request) {
    	// Allows requests only for the root path ("/") to prevent duplicate calls.
    	if r.RequestURI != "/" {
    		http.NotFound(w, r)
    		return
    	}
    
    	var session session
    	var doc *firestore.DocumentRef
    
    	isNewSession := false
    
    	ctx := context.Background()
    
    	client, err := firestore.NewClient(ctx, a.projectID)
    	if err != nil {
    		log.Fatalf("firestore.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	// cookieName is a non-empty identifier for this app, it is used as the key name
    	// that contains the session's id value.
    	//
    	// Set it to something more descriptive for your app.
    	cookieName := "session_id"
    
    	// If err is different to nil, it means the cookie has not been set, so it will be created.
    	cookie, err := r.Cookie(cookieName)
    	if err != nil {
    		// isNewSession flag is set to true
    		isNewSession = true
    	}
    
    	// If isNewSession flag is true, the session will be created
    	if isNewSession {
    		// Get unique id for new document
    		doc = client.Collection(a.collectionID).NewDoc()
    
    		session.Greetings = greetings[rand.Intn(len(greetings))]
    		session.Views = 1
    
    		// Cookie is set
    		cookie = &http.Cookie{
    			Name:  cookieName,
    			Value: doc.ID,
    		}
    		http.SetCookie(w, cookie)
    	} else {
    		// The session exists
    
    		// Retrieve document from collection by ID
    		docSnapshot, err := client.Collection(a.collectionID).Doc(cookie.Value).Get(ctx)
    		if err != nil {
    			log.Printf("doc.Get error: %v", err)
    			http.Error(w, "Error getting session", http.StatusInternalServerError)
    			return
    		}
    
    		// Unmarshal documents's content to local type
    		err = docSnapshot.DataTo(&session)
    		if err != nil {
    			log.Printf("doc.DataTo error: %v", err)
    			http.Error(w, "Error parsing session", http.StatusInternalServerError)
    			return
    		}
    
    		doc = docSnapshot.Ref
    
    		// Add 1 to current views value
    		session.Views++
    	}
    
    	// The document is created/updated
    	_, err = doc.Set(ctx, session)
    	if err != nil {
    		log.Printf("doc.Set error: %v", err)
    		http.Error(w, "Error creating session", http.StatusInternalServerError)
    		return
    	}
    
    	if err := a.tmpl.Execute(w, session); err != nil {
    		log.Printf("Execute: %v", err)
    	}
    }
    

    다음 다이어그램에서는 Firestore가 Cloud Run 앱의 세션을 처리하는 방법을 보여줍니다.

    아키텍처 다이어그램: 사용자, Cloud Run, Firestore

세션 삭제

Google Cloud 콘솔에서 세션 데이터를 삭제하거나 자동 삭제 전략을 구현할 수 있습니다. Memcache 또는 Redis와 같은 세션의 스토리지 솔루션을 사용하면 만료된 세션이 자동으로 삭제됩니다.

로컬에서 실행

  1. 터미널 창에서 sessions 바이너리를 빌드합니다.

    go build
    
  2. HTTP 서버를 시작합니다.

    ./sessions
    
  3. 웹 브라우저에서 앱을 확인합니다.

    Cloud Shell

    Cloud Shell 툴바에서 웹 미리보기 웹 미리보기를 클릭하고 포트 8080에서 미리보기를 선택합니다.

    로컬 머신

    브라우저에서 http://localhost:8080으로 이동합니다.

    'Hello World', 'Hallo Welt', 'Hola mundo', 'Salut le Monde' 또는 'Ciao Mondo'의 다섯 가지 인사말 중 하나가 표시됩니다. 페이지를 다른 브라우저나 시크릿 모드로 열면 언어가 변경됩니다. Google Cloud 콘솔에서 세션 데이터를 보고 수정할 수 있습니다.

     Google Cloud 콘솔의 Firestore 세션

  4. HTTP 서버를 중지하려면 터미널 창에서 Control+C를 누르세요.

Cloud Run에서 배포 및 실행

Cloud Run을 사용하면 데이터 양이 많고 부하가 과도한 상황에서도 안정적으로 실행하는 앱을 빌드 및 배포할 수 있습니다.

  1. Cloud Run에 앱을 배포합니다.
        gcloud run deploy firestore-tutorial-go 
    --source . --allow-unauthenticated --port=8080
    --set-env-vars=GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
  2. 이 명령어로 반환한 URL에 방문하여 페이지 로드 간에 세션 데이터가 유지되는 방법을 확인합니다.

이제 Cloud Run 인스턴스에서 실행되는 웹 서버에서 인사말을 전달합니다.

앱 디버깅

Cloud Run 앱에 연결할 수 없는 경우 다음 사항을 확인하세요.

  1. gcloud 배포 명령어가 성공적으로 완료되었고 오류를 출력하지 않았는지 확인합니다. 오류가 있으면(예: message=Build failed) 오류를 수정하고 Cloud Run 앱 배포를 다시 시도합니다.
  2. Google Cloud 콘솔에서 로그 탐색기 페이지로 이동합니다.

    로그 탐색기 페이지로 이동

    1. 최근에 선택한 리소스 드롭다운 목록에서 Cloud Run 애플리케이션을 클릭한 후 전체 module_id를 클릭합니다. 앱을 방문했을 때의 요청 목록이 표시됩니다. 요청 목록이 표시되지 않는 경우 드롭다운 목록에서 전체 module_id를 선택했는지 확인합니다. Google Cloud 콘솔에 오류 메시지가 표시되면 앱 코드가 웹 앱 작성 섹션의 코드와 일치하는지 확인합니다.

    2. Firestore API가 사용 설정되어 있는지 확인합니다.

삭제

프로젝트 삭제

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Cloud Run 인스턴스 삭제

  1. In the Google Cloud console, go to the Versions page for App Engine.

    Go to Versions

  2. Select the checkbox for the non-default app version that you want to delete.
  3. 앱 버전을 삭제하려면 삭제를 클릭합니다.

다음 단계