CodeGym /행동 /Go SELF /r . Context ()reul tonghan yocheong chwiso wa olbareun ch...

r . Context ()reul tonghan yocheong chwiso wa olbareun cheori

Go SELF
레벨 63, 레슨 3
사용 가능

1. Yocheong kontegeuseuteu wa geu chwiso

Seobeoreul “gam-euro” jaksseobhaetdamyeon, handlerneun seongsilhan ilkkuncheoreom boibnida: yocheong-eul batgo, jageob-eul hago, eungdab-eul dollyeojumnida. Hajiman hyeonsireun naenghokhabnida. keullaieonteuga taeb-eul dat-eul sudo itgo, mobail neteuwokeuga kkeun-gil sudo isseumyeo, lodeu baelleonseoga yeongyeol-eul kkeun-eul sudo inneunde, seobeoneun yeojeonhi gyesan-eul gyesokhago, jeojangso-e jeopgeunhago, JSON-eul pomaettinghago isseul su itsseumnida.

Gyeolguk imi jonjaehaji anneun yocheong-e CPUwa memorieul sseuge doego, geurigo naseo “bunmyeong sayongja su-neun manhji aneun geot gateunde” seobeoga wae ireoke beogeowohaneunji isanghage doemnida.

Go-ui gwanjeom-eseo yocheong chwiso-neun mabeopdo, “busu hyogwa”do animnida. Igeoseun yocheong-ui context.Contextreul tonghae jeondaldoeneun sinhoimnida. Go seobeo jjeog-eseoneun oraejeonbuteo ireoke habuihae watseumnida: “jageob-i deo isang pilyo eopdamyeon, kontegeuseuteuro allyeora.” Igeoseun sinroeong-ui haeksim yoso jung hanabnida. kontegeuseuwa deadline-i eopseumyeon seobeoneun cheorihaeya hal jageob “bit”eul ssahgi sijakhago gyeolguk risoseu hange e budichigi swibseumnida.

Saengmyeongjugineun eotteoke boilkka

Geurimeuro tteoolligi swipge, daeumgwa gateun saengmyeongjugi heureum-eul meorisoge dueumyeon pyeonhamnida:

flowchart TD
    A[keullaieonteuga yocheong jeonsong] --> B[Handlerga r *http.Request susin]
    B --> C["ctx := r.Context() hwagdeuk"]
    C --> D[ctxreul app/storagero jeondal]
    D --> E{ctx chwisodoem?}
    E -- anio --> F[jageob suhaeng hu eungdap]
    E -- ye --> G[jungdanhago jonglyo]

r.Context()neun mueosimyeo eonje chwisodoelgga

r.Context()neun teukjeong HTTP yocheong-ui kontegeuseuteuimnida. Igeoseul “gapseuro pyohyeondoen yocheong-ui saengmyeongjugi”ra go saenggakhal su itsseumnida. net/http naebueseo kontegeuseuteuneun http.Requeste mukkyeo itsseumnida. Yeoksa-jeogeuro contextga Go-e deoi bdwieosseul ttae APIreul kkaeji anki wihae ireoke seolgyehaetseumnida.

Kontegeuseuteuga yuyonghan iyuneun du gaji sinal-eul damgo itgi ttaemun-imnida.

Cheotjjaero, chwiso sinalimnida: ctx.Done()neun chwiso sig jehaphaneun chaeneol-eul banhwanhamnida. Duljjaero, chwiso woninimnida: ctx.Err()neun mueosi il-eonanneunji seolmyeonghaneun oryureul banhwanhamnida. ilbanjeogeuro context.Canceled ttoneun context.DeadlineExceededimnida.

Silmujeogeuro r.Context()neun daecheoro ireon sanghwang-eseo chwisodoemnida: keullaieonteuga yeongyeol-eul kkeonneotgeona, seobeoga shutdown-eul sijakhaetgeona, yocheong taimaut-i jinaetgeona, ttoneun yeoreobuni seuseuro georeon “naebu” deadline-i manryodoeeotgeona. Jeonghwakhi mueosi il-eonanneunji majchul pilyoneun eopseumnida. Jungsineun olbareuge daeeunghaneun geotimnida: ppalli jageob-eul jungdanhago bulpilyohan il-eul haji anneun geosimnida.

Mini demo: ctx.Err()reul geunyang ilgeobnida.

package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("ctx err:", r.Context().Err()) // ctx err: <nil>
	_, _ = w.Write([]byte("ok\n"))
}

2. handlerreul wihan gibon gyuchik

r.Context()reul context.Background()ro bakkuji maseyo

Cheoeum sijakhal ttaeneun ireoke saenggakagi swibseumnida: “naege kontegeuseuteuga pilyohae? geureom context.Background()reul sseuji mwo.” Hajiman igeoseun HTTP kodeueseo geoui hangsang silsuimnida.

context.Background()neun kontegeuseuteu teuri-ui ppurimyeo, jeoldaero chwisodoeji anseumnida. Jeuk, r.Context()reul Background()ro bakkwotdamyeon, gajang jungyohan sinal-eul beorin geosimnida: “keullaieonteuga tteonatda / i yocheong-eun deo isang pilyo eopda.”

handler an-eseoui olbareun sijageun geoui hangsang gatsseumnida: ctx := r.Context()reul gajyeogo, geu dwi-ro app gyecheung, storage, oebu hoechul deung modeun gyecheung-euro geugeoseul “tonghaengjeung”cheoreom jeondalhamnida. oneul storagega danji “memori sog slice”igo lock-ina neteuwokeu hoechuri eopdeorado machangajimnida. Jigeum ikhineun seupgwani najunge maeu manh-eun siganeul jeol-yakhae jubnida.

Choeso paeteon golgyeok:

package main

import (
	"net/http"
)

func listTasksHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	if err := ctx.Err(); err != nil {
		return
	}

	_ = ctx // ihu app gyecheung-euro jeondal
	_, _ = w.Write([]byte("todo\n"))
}

if err := ctx.Err(); err != nil { return } bubuneul jalmyeongsi boseyo. yocheong chogi-eneun geoui hangsang nilijiman, handlerga bokjaphageona heungmirowun sanghwang-eseo hoechuldoel su itdamyeon ireon “gadeu geomsa”ga yuyonghamnida. yeoreul deureomyeon keullaieonteuga geoui jeuksi yeongyeol-eul kkeun-eobeorin gyeonguimnida.

ctx.Err()e ttareun iljjik banhwan

Jinan gang-ui-deuleseo urineun guard clause-reul manhi sseotseumnida: “oryuga isseumyeon dollaeseo banhwanhara.” kontegeuseuteudo gateumnida: “kontegeuseuteuga chwisodoeeotdamyeon dollaseo banhwanhara.” Jungyohan geoseun chwiso-neun “seobeo oryu”ga anira, gyesokhaedo uimiga eopdaneun sinhoraneun jeom-imnida.

Kodeuga munjangcheoreom ilhige jak-eun doumireul dumyeon pyeonhamnida:

package main

import "context"

func isCanceled(ctx context.Context) bool {
	return ctx.Err() != nil
}

Geurigo handlereseo ireoke sayonghamnida:

package main

import (
	"net/http"
)

func createTaskHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	if isCanceled(ctx) {
		return
	}

	// JSON ilgi, geomjeung, jeojang...
	_, _ = w.Write([]byte("created\n"))
}

I bangsik-i joeun iyuneun, keullaieonteuga imi tteonatda-myeon “naneun bandeusi eungdabhaeya hae”ra go gajanghaji anneundaneun jeom-imnida. Chobojadeureun gakkeum “geuraedo JSON oryureul dollyeojwo야ji”ra go saenggakhajiman, imi yeongyeol-i datyeo itdamyeon nugu-do boji mot-hal eungdab-eul yeppuge mandeuneuraneun siganman sseuge doemnida.

ctxreul gyecheung jeonche-ro jeondalhaseyo

r.Context()ui gajang keun silmuyong gachineun igeoseul gyecheung araero gyesok jeondalhal ttae naotnida. Cheoeumeneun jimhan geotcheoreom boibnida: sig-neocheo-e maebeon han gaeui paeramiteoga deo butseumnida. Geureona daesineun jageob-eul jal tongjehal su itge doemnida. chain-ui eotteon dangye-do jeolmyeonghal ttae jeomsin-e stop hal su itsseumnida.

Yeoreul deureo, “task tracker” hakseubyong aebpeullikeisyeongwa seobiseuga itdago hapsida:

package app

import "context"

type TaskService struct {
	// storage mit gita uijonseong
}

func (s *TaskService) List(ctx context.Context) ([]Task, error) {
	_ = ctx
	return nil, nil
}

Yeogi-seo juimokhal jeomeun ctxga gureu cheong-uip hild-ga anira meoseodeu-ui paeramiteoraneun geosimnida. Igeosi jungyohamnida. kontegeuseuteuneun geugeosi sayongdoeneun teukjeong jageobboda deo gilge “sal-a” isseumyeon andoemnida. Boitong gujochae an-e kontegeuseuteureul jeojanghaneun geoseun joeun saenggagi animnida: saengmyeongjugiga seokkigo, hoechulhan kodeuga deadlinegwa chwiso-e daehan tongjereul ilhge doemnida.

handler sujun-eseoneun ireoke boibnida:

package httpapi

import (
	"context"
	"net/http"
)

type TaskLister interface {
	List(ctx context.Context) ([]any, error) // yesireul wihae dansunhwa
}

type Handlers struct {
	Service TaskLister
}

func (h *Handlers) list(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	_ = ctx

	_, _ = w.Write([]byte("ok\n"))
}

Silje kodeueseoneun mullon jeongsangjeogin taibeul sseul geosimnida. []any daesin []Taskwa gateun hyeongtae malimnida. Hajiman aidi-eoneun han gajibnida: kontegeuseuteuneun jageob-ui cheot beonjjae inja-ro araero heulleogamnida.

3. Orae geollineun jageobgwa chwiso hwagin

Gakkeum-eun sigani geolineun jageob-eul hal ttaega itsseumnida: keun listeu pilteoring, impeoteu, bogoseo saengseong, “neullin” diseukeu sseugi, neteuwokeu hoechul deungimnida. jigeum-eun geugeoseul Sleepeuro heunnae naego itdago haedo machangajimnida. selectwa chaeneol-eul sseuji anado, yocheong chwiso-e “yeouihage” daeeunghal su itsseumnida: jageob-eul jakge kkeunnaeseo bunhalhago, bunhal sai-sai-e ctx.Err()reul hwaginhaseyo.

Ye: mugeoun jageob-eul 5danggye-ro heunnae naebomnida.

package app

import (
	"context"
	"time"
)

func slowCompute(ctx context.Context) error {
	for i := 0; i < 5; i++ {
		if err := ctx.Err(); err != nil {
			return err
		}
		time.Sleep(200 * time.Millisecond)
	}
	return nil
}

Yeogineun teukbyeolhan mabeobi eopseumnida. Geureona hyogwaneun keumnida. keullaieonteuga cheot beonjjae danggye-eseo tteonatdamyeon, “imi sijakhaesseunikka 1cho deo gyesanham” gat-eun geos-euro meomchaji anseumnida. geoui baro jageob-eul jungdanhago risoseureul haebanghamnida.

handlereseoneun ireoke doemnida:

package httpapi

import (
	"net/http"
)

func slowHandler(w http.ResponseWriter, r *http.Request) {
	if err := slowCompute(r.Context()); err != nil {
		return
	}
	_, _ = w.Write([]byte("done\n"))
}

4. context.WithTimeout()eul tonghan naebu taimaut

Gakkeum yocheong chwiso-neun “oebu ibenteu”imnida. keullaieonteuga tteonan geos-iyeoyo. Hajiman gakkeumeun yocheong an-ui teukjeong jageob siganeul seuseuro jegmyeonghago sip-eul ttaedo itsseumnida. Yeoreul deureo, “jeojangso-eseo task ilgeoneun 300msboda deo geollyeoseoneun andoenda. geureoji antamyeon yeongyeol-eul butjabeuneun geotboda oryureul dollyeojuneun ge deo natda”wa gateun gyeonguimnida.

Jungyohan jeom-eun ban-deusi ireoke haeyahandaneun geosimnida: busang kontegeuseuteuro r.Context()reul sseoya hamnida. Geuraeya saengmyeongjugi yeongyeoli yujidoemnida: “yocheong-i jugeumyeon, jasin-ui jason jageobdo hamkke jukneunda.”

package httpapi

import (
	"context"
	"net/http"
	"time"
)

func handler(w http.ResponseWriter, r *http.Request) {
	opCtx, cancel := context.WithTimeout(r.Context(), 300*time.Millisecond)
	defer cancel()

	_ = opCtx
	_, _ = w.Write([]byte("ok\n"))
}

I paeteon-i gachiga inneun iyuneun du gajimnida. Cheotjjaero, defer cancel()neun jageob-i iljjik kkeutnasseodo taimeo risoseureul haebanghae jubnida. Duljjaero, ilban oryuwa taimaut-eul gubunhal su itsseumnida: errors.Is(err, context.DeadlineExceeded).

5. Chwiso wa HTTP eungdap

context.Canceledwa context.DeadlineExceededreul eotteoke dallya halkka

Jeongmal gat-eun pyoreul gajigo sip-eojimnida: “eotteon oryu → eotteon HTTP status.” Mureon yu-yonghajiman, i geoseul gwallyojuuijeog jeolcha-ro mandeulji anneun geosi jungyohamnida. Yocheong chwiso maengnag-eseoneun siljujeog choeso seon-i itsseumnida.

context.Canceled sanghwang-eseoneun daecheoro keullaieonteuga imi tteonatgo, mulrijeogeuro do olbareun eungdab-eul bonael su eopseumnida. Ttaemune gajang haprijeogin haengdong-eun jageob-eul meomchu-go joyonghi nappeojineun geotimnida. piryohamyeon debug sujun-euro rogeureul namgil su issjiman, “seobeo oryu”ro gijaehal piryoneun eopseumnida.

context.DeadlineExceeded sanghwang-eseoneun nugu-ui deadline-inji ihaehaeya hamnida. Ige yocheong deadline-imyeon, yeoreul deureo seobeo-ui WriteTimeoutina keullaieonteu taimaut-gwa gateun gyeongu, geurim-eun biseuthamnida. keullaieonteuga imi gidariji mot-hal sudo itsseumnida. Hajiman ige yeoreobun jasin-ui naebu jageob taimautimyeon, WithTimeouteuro georeo dun geot-iya, ajik jeongdon-doen oryureul bonael sigan-i nam-a isseul sudo itsseumnida. Ireon gyeongu jaju 504 (Gateway Timeout) ttoneun 503 (Service Unavailable)reul sayonghajiman, gyoyuk yong peurojekteu-eseoneun wonchigeul ihaehaneun geosi deo jungyohamnida: igeoseun “500 internal”i anibnida, waenyamyeon siseutemeun jeongsangjeogeuro dongjakhaetgo danji sigan jegyakeul neomeosseul ppun-igi ttaemun-imnida.

Jjag-eun cheat sheetro daum pyoreul chamjohae boseyo:

ctx.Err() Botong mueoseul uimihaneunga handlereseo hal il
nil
yocheong-i sal-a isseum, jageob gyesok gyesok jinhaeng
context.Canceled
keullaieonteuga tteonam / yocheong chwisodoem jageob jungdan hu jonglyo
context.DeadlineExceeded
yocheong ttoneun jageob-ui deadline chogwa jageob jungdan; naebu taimaut-imyeon jeongdon-doen oryureul banhwanhal su iss-eum

ResponseWriterwa gwallyeon-doen nuanseu

Chobojadeureun maeu inganjeogin maeumeul gajimnida: “geuraedo na-neun JSON-eul dollyeojwoya hae!” Munjeneun kontegeuseuteuga chwisodoeeosseumyeon we sseuneun jageob-i oryuro kkeutnal su istdaneun geosimnida. yeoreul deureo broken pipega nareul su issseumnida. Gisuljeogeuro-neun sseugi oryureul musihal su itjiman, deo olbareun bangbeobeun jeondaldoeji anh-eul eungdab ttaemune mugeoun jageob-eul hajineun geosimnida.

Geuraeseo silmujeog yop-eun ireotsseumnida: keun eungdab-eul mandeulgi jeon-e sort, JSON marshaling, pyohyeon deiteo jeongsin deung-eul hagi jeon-e han beon deo ctx.Err()reul hwaginhaneun geosimnida. Eungdab-i keugeona mandeuneun de sigan-i manhi geollil ttae teukhi yuyonghamnida.

package httpapi

import (
	"net/http"
)

func safeWrite(w http.ResponseWriter, r *http.Request, b []byte) {
	if err := r.Context().Err(); err != nil {
		return
	}
	_, _ = w.Write(b)
}

“Silje” kodeueseoneun yeoreobun-ege writeJSON gateun heolpeoga isseul geosigo, geugose ireon geomsa-reul neoh-eul su itsseumnida. Igeoseun “silver bullet”i anira majimak saneunghan pilteo-imnida: “yocheong-i jugeosseumyeon, eungdab-eul yes쁘ge geuriji anneunda.”

6. Yese

Ijeneun i modeun geoseul han beonjjeogeuro ieoboseumnida. Yaksigan deo oraegellineun “task export” handlerga itdago sangsanghaebosyeo. Urineun naebu jageob taimaut-eul geolgo, chwiso-reul jonjunghadorok jageob-eul “nuneo-seo” cheorihamnida.

package httpapi

import (
	"context"
	"net/http"
	"time"
)

func exportHandler(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
	defer cancel()

	if err := slowCompute(ctx); err != nil {
		return
	}

	_, _ = w.Write([]byte("exported\n"))
}

Ne, yeogieseo-neun ajik JSON envelope-na areumdaun oryureul daruji anseumnida. geurigo oneul gang-ui-ui chokjeom-euroseo-neun geuge jeongsang-imnida. Gajang jungyohan mokpyoneun seupgwan-eul mandeuneun geosimnida: modeun handlerneun “kontegeuseuteuga sal-a inneun dongan jageob-eul hago, jugeumyeon deurama eopshi tteonanda”neun gyeyage ttara dongjakhanda.

7. Yocheong chwiso cheori si heunghan silsu

Silsu 1: r.Context() daesin context.Background() sayong.
Ireon silsu-neun “il dan doragage” haryeogo jaju hanneun pyeon-imnida. teukhi kodeu arae jjeok-e ctxreul neomgyeoya haneunde “eojjeonji eopseul ttae” deo geureotseumnida. Hajiman i daechi-ui daeganeun keumnida. gajang jungyohan ganeungseong, jeuk yocheong-i deo isang pilyo eopseul ttae meomchul su inneun ganeungseong-eul beorige doemnida. Gyeolguk seobeoneun keullaieonteuga tteonan dwi-edo mugeoun jageob-eul gyesokhal su itgo, jeomjeom bulpilyohan gyesan gongjang-euro byeonhae gal su itsseumnida.

Silsu 2: cheoeum han beon-man chwiso-reul geomsahago geu dwi-ro itneun geot.
handler-ui cheot jul-e if ctx.Err() != nil { return }reul duneun geoseun yuyonghajiman, geu dwi-e gin cheoriga isseumyeon geugeoseuro chungbunhaji anseumnida. kontegeuseuteuneun eonjedeunji chwisodoel su itsseumnida. Geuraeseo “orae geollineun” logic-eseoneun bunhal cheoriga pilyohamnida: loop, stage, step, geurigo geu saisaie ctx.Err() hwagin. geuraeya chwiso-ga jangsigyong deung-i anira jinsilhan emergency brake-cheoreom dongjakhabnida.

Silsu 3: context.Canceledil ttaedo “bandeusi eungdab-eul banhwanharyeogo” hagi.
Keullaieonteuga yeongyeol-eul dat-assdamyeon, ije yeoreobun-eun “areumdapge jaksahaneun” il-e daehan uimuna neunlyeogi eop-seul su itsseumnida. I sungan JSON marshaling-eul hago, hedeoreul sseugo, geugeoseul “seobeo oryu”ro roginghaneun geoseun daecheoro sanghwang-eul deo nappeuge mandeumnida: risoseuneun deo sseugo, log-eneun jan-sori man neu-reonamnida. Deo olbareun bangbeobeun geunyang jageob-eul meomchu-go nappeojineun geosimnida.

Silsu 4: context.Context reul seobiseu na jeojangso gujochae an-e boyuhaneun geot.
Igeoseun paeramiteoreul julineun pyeonhan “choejeokhwa”cheoreom boibnida: han beon structe neoh-eumyeon, deo isang jeondalhaji anado doemnida. Hajiman geureohge hamyeon saengmyeongjugiga seokkigo, hoechulhan kodeuga deadline tongjereul ilhge doemnida. kontegeuseuteuneun teukjeong jageob-ui paeramiteo-yeoya haji, gaekche “eodin-ga an”e sumgyeojin pild-ga doeeoseoneun andoemnida. Geuraeseo Go-eseoneun ilbanjeogeuro Do(ctx, ...)reul sseuji, “han beon neohgo itneun” bangsigeul sseuji anseumnida.

Silsu 5: WithTimeout()euro taimaut-eul georeodo cancel()reul ij-eobeorineun geot.
Jageob-i seonggongjeogeuro kkeutnasseodo, taimeo-wa geuwa yeonggyeoldoen giban guseong-eun haebangdoeeoya hamnida. defer cancel()reul haji anheumyeon nop-eun buha-eseo risoseuga gyesok ssah-il su itsgo, geugeoseun geujeo “mwonga isanghan nu-su”cheoreom boyeo geumyoil jeonyeok-e chatgi silheun munjega doemnida.

1
과제
Go SELF, 레벨 63, 레슨 3
잠금
요청 펄스
요청 펄스
1
과제
Go SELF, 레벨 63, 레슨 3
잠금
취소 서비스
취소 서비스
1
과제
Go SELF, 레벨 63, 레슨 3
잠금
Cheori step
Cheori step
1
과제
Go SELF, 레벨 63, 레슨 3
잠금
리포트 타임아웃
리포트 타임아웃
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION