Context in golang
Context
golang์ ์จ๋ดค์ผ๋ฉด ๋ค๋ค ํ ๋ฒ์ฏค ์ฌ์ฉํ๊ฒ ๋๋๊ฒ์ด ๋ฐ๋ก context.Context ์ด๋ค.
go์์๋ context๋ฅผ ์ด๋ป๊ฒ ์ฌ์ฉํ๊ณ ์ด๋ป๊ฒ ์ค๊ณํ์์ง ์ดํด๋ณด์.
๊ณต์๋ฌธ์๋ฅผ ์ฝ์ผ๋ฉด์ ์ดํด๋๋ฅผ ๋์ฌ๋ณด์.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
context ํจํค์ง๋ API ๊ฒฝ๊ณ๋ฅผ ๋์ด ํ๋ก์ธ์ค ๊ฐ์ deadline, ์ทจ์ signal ๋ฐ ๊ธฐํ ์์ฒญ ๋ฒ์ ๊ฐ์ ์ ๋ฌํ๋ ์ปจํ
์คํธ ์ ํ์ ์ ์ํฉ๋๋ค.์ปจํ ์คํธ๋ ์ฐ๋ฆฌ ๋ง๋ก ๋ฌธ๋งฅ, ๋งฅ๋ฝ์ ๋ปํ๋ค. REST ์์ฒญ์ด๊ฑด, ์์ผ ์์ฒญ์ํ๊ฑด, ์์ฒญ-์๋ต์ ํ๋ฆ ์์์ ์ ์งํด์ผ ํ ์ํ๋ฅผ context๋ฅผ ํตํด ๊ณต์ ํ๋ค.
Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context.
์๋ฒ๋ก ๋ค์ด์ค๋ ์์ฒญ์ ์ปจํ
์คํธ๋ฅผ ์์ฑํ๊ณ ์๋ฒ๋ก ๋๊ฐ๋ ํธ์ถ์ ์ปจํ
์คํธ๋ฅผ ์๋ฝํด์ผ ํฉ๋๋ค.
The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue.
์ด๋ค ์ฌ์ด์ ํจ์ ํธ์ถ ์ฒด์ธ์ ์ปจํ
์คํธ๋ฅผ ์ ํํด์ผ ํ๋ฉฐ ์ ํ์ ์ผ๋ก WithCancel, WithDadline, WithTimeout ๋๋ WithValue๋ฅผ ์ฌ์ฉํ์ฌ ๋ง๋ ํ์ ์ปจํ
์คํธ๋ก ๋์ฒดํด์ผ ํฉ๋๋ค.
When a Context is canceled, all Contexts derived from it are also canceled.
์ปจํ
์คํธ๊ฐ ์ทจ์๋๋ฉด ์ปจํ
์คํธ์์ ํ์๋ ๋ชจ๋ ์ปจํ
์คํธ๋ ์ทจ์๋ฉ๋๋ค.์ฆ, ์์ฒญ์ด ๋ค์ด์ค๋ฉด ์ปจํ ์คํธ๋ฅผ ์์ฑํ๊ณ , ์์ฒญ์ด ๋๋๋ฉด ์ปจํ ์คํธ๋ฅผ ์ข ๋ฃ์ํค๊ฒ ๋ค๋ ๋ป์ด๋ค.
์์์ ์๊ธฐํ๋ ์์ฒญ-์๋ต์ ํ๋ฆ์ ์ค์ ์ผ๋ก ๋ณด์. ๋ชจ๋ API๋ ์์ฒญ๊ณผ ์๋ต์ด ์๋ค. ํ๋์ ์์ฒญ ์์์๋ ๋ถ๊ธฐํด์ ๋ง์ ๋ก์ง์ ์ํํ ์ ์๋ค. ๊ทธ๋ ๊ฒ๋๋ฉด ํ๋์ ์์ฒญ-์๋ต ์ฌ์ด์๋ ์๋ง์ ์์ฒญ2-์๋ต2, ์์ฒญ3-์๋ต3โฆ ์ด ์๊ธฐ๊ฒ ๋๋ค.
ํ๋์ ์์ฒญ-์๋ต์ด ํ๋์ lifecycle์ ๊ฐ์ง๋ค๊ณ ํ์๋ root๋ก ๋ถํฐ context๋ฅผ ํ์์์ผ๊ฐ๋ฉด ๋ง์ API์ lifecycle์ ๊ด๋ฆฌํ ์๊ฐ ์๋ค.
WithCancel,WithDeadline,WithTimeout,WithValue๋ฅผ ์ด์ฉํด์ ํ์์ํค๊ณ , ๊ด๋ฆฌํ๋ฉด ๋ ๊ฒ์ด๋ค.
cancel() ํจ์๋ฅผ ์คํํ๋ฉด ์์๋ค์ด ์ ๋ถ ์ทจ์๋ ๊น?
์ค์ ๋ก ๋์ ์์ฒด๋ฅผ ๋ฉ์ถ๋ ๊ฒ์ ์๋๊ณ , context๊ฐ ์ทจ์๋๋ค. ์์ ํจ์๊ฐ ๋ฐ๋ก ์ข ๋ฃ๋์ง๋ ์๋๋ค.
์ปจํ ์คํธ ์์ฒด๋ฅผ ์ทจ์ ์ฒ๋ฆฌํ๊ณ ์๋ฌ๋ฅผ ๊ธฐ๋กํ๋ค.
์ปจํ ์คํธ๋ฅผ ์ฌ์ฉํ๋ ์์ ์ ๋ํ ๊ฒ์ด๋ค.
context.Context์์ฒด๊ฐ ์ธํฐํ์ด์ค๋ค. ๋ฐ๋ผ์ ๋ณธ์ธ์ด ๊ตฌํํ ์์ฒด Context๋ฅผ ์ฌ์ฉํ๋๋ผ๋ ์ด๋ฌํ ์ฌํญ์ ๋ํด์ ์งํค๋ฉฐ ๊ฐ๋ฐ์ ํ๋ฉด ์ข์ ๊ฒ์ด๋ค.
go ์ธ์ด์ ์ฒ ํ์ค์ ์ด๋ฐ ๋ง์ด ์๋ค.
๋ฉ๋ชจ๋ฆฌ ๊ณต์ ๋ฅผ ํตํด ์ปค๋ฎค๋์ผ์ด์
ํ์ง ๋ง๊ณ , ์ปค๋ฎค๋์ผ์ด์
์ ํตํด ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ณต์ ํ๋ผ.
์๋ก ๋ค๋ฅธ ํ๋ก์ธ์ค, API, ํจ์ ๋ฑ์์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ณต์ ํ๊ฒ ํ๋ ๊ฒ์ด ์๋๋ผ, ์ปจํ ์คํธ๋ฅผ ํตํด ์ปค๋ฎค๋์ผ์ด์ ์ ํ์ฑํ๋ฉด ์ด๋ฌํ ์ฒ ํ์ ๋ฌ์ฑํ ์ ์์๊ฒ์ด๋ค.
Last updated