Print
카테고리: [ Development ]
조회수: 30549

개요

golang은 Context(컨텍스트) 패키지를 기본적으로 포함하고 있다. 컨텍스트는 함수가 요청을 받을 때 API와 API 사이, 프로세스 사이에서 값들을 가지고 다닌다. 

서버에 요청이 들어오면 Context가 생성이 되며, 함수가 다른 함수를 호출할 때 반드시 Context가 전파된다. 이 경우 WithCancel, WithDeadline, WithTimeoout, WithValue로 Context의 값을 변경할 수 있으며 Context가 취소되는 경우 해당 Context로부터 파생된 Context도 삭제된다. 

 

Context 생성

컨텍스트는 생성 후 값을 변경할 수 없다. 

context.Background: 값이 없는 컨텍스트를 기본으로 생성한다. 생성 시 취소되지 않는다. 

context.WithValue: 특정 key와 value를 갖는 컨텍스트를 생성한다.  

context.TODO: Background와 마찬가지로 빈 컨텍스트를 생성한다. 어떤 컨텍스트를 사용할지 불명확할 때 사용한다. 

context.WithCancel: 취소신호를 수신할 수 있는 컨텍스트를 생성한다. 

context.WithDeadline/WithTimeout: 컨텍스트가 특정 시간 이후 자동으로 취소되도록 생성한다. 

 

예시

golang으로 GCP Cloud Functions에서 Firestore를 사용하는 예시이다. 

func FirestoreInsert(w http.ResponseWriter, r *http.Request) {
        var resource entity
        ctx := context.Background()
        client, err := firestore.NewClient(ctx, os.Getenv("GCP_PROJECT"))
        if err != nil {
                log.Println(`{"message": "Firestore Connection Failed", "severity": "error","detail":`,err,'}')
                http.Error(w,"Firestore Connection Failed",500)
                return
        }

 

Firestore 클라이언트를 생성하기 전에, context.Background()를 생성한다. 생성한 컨텍스트(ctx)를 firestore.NewClient()의 입력값으로 전달한다. 

dbCollection := client.Collection("resources")
cur := dbCollection.Doc(paramName[0])
_, deleteErr := cur.Delete(ctx)

 

https://golang.org/pkg/context/

https://jaehue.github.io/post/how-to-use-golang-context/