Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ふんわり理解するcontext

 ふんわり理解するcontext

https://connehito.connpass.com/event/251002/ で使用したLTの資料です。

参考書籍のURL
・公式ドキュメント
https://pkg.go.dev/context
・『Go Currency Patterns : Context』
https://go.dev/blog/context
・『改訂2版 みんなのGo言語』
https://gihyo.jp/book/2019/978-4-297-10727-7
・『Learning Go: An Idiomatic Approach to Real-World Go Programming』
https://www.amazon.co.jp/dp/1492077216

TwitterID:@rukiadia

July 06, 2022
Tweet

More Decks by TwitterID:@rukiadia

Other Decks in Programming

Transcript

  1. ͜͏͍͏ίʔυɺݟͨ͜ͱ͋Γ·ͤΜ͔ʁ func logic(ctx context.Context, info string) (string, error) { //

    ctxΛ༻͍ͯԿ͔͠ΒͷॲཧΛ࣮ߦ return "", nil } ༨ஊ DPOUFYU$POUFYUΛୈҰҾ਺ʹ౉͢ͷ͸ (Pͷ׳श
  2. DPOUFYUͷΠϯλϑΣʔε type Context interface { // ఀࢭ͕εέδϡʔϧ͞Εͨ࣌ؒɺεέδϡʔϧ͞Ε͍ͯΔ͔Ͳ͏͔ͷbooleanΛฦ٫ Deadline() (deadline time.Time,

    ok bool) // λΠϜΞ΢τɺΩϟϯηϧͳͲʹΑΔcontextͷ׬ྃΛ௨஌͢Δνϟωϧ Done() <-chan struct{} // ׬ྃͨ͠ཧ༝Λฦ٫͢Δ Err() error // key:valueͰอ͍࣋ͯ͠Δ஋Λฦ͢ Value(key interface{}) interface{} }
  3. λΠϜΞ΢τͤ͞ΔDPOUFYUΛॻ͍ͨྫ func main() { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer

    cancel() start := time.Now() <-ctx.Done() // contextͷऴྃΛνϟωϧͰड͚औΔ end := time.Now() fmt.Println(end.Sub(start)) // 3s ͱදࣔ͞ΕΔ }
  4. )551ϦΫΤετͷλΠϜΞ΢τྫ func getHTTPResponse(url string) (*http.Response, error) { ctx, cancel :=

    context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // contextΛΩϟϯηϧ client := &http.Client{} req, _ := http.NewRequest("GET", url, nil) res, err := client.Do(req.WithContext(ctx)) if err != nil { // Ϩεϙϯεऔಘ·Ͱʹ10ඵ͕ܦաͨ͠৔߹ɺ͜͜ͰΤϥʔ // ctx.Err()͕ʮcontext deadline exceededʯΛฦ݁͢ՌʹͳΔ return nil, err } return res, nil } ༨ஊ DPOUFYUͷ༻్͕HPSPVUJOFʹݶఆ͞Εͳ͍ ͜ͱ͕ݟͯͱΕΔ
  5. )551ϦΫΤετͷλΠϜΞ΢τͷิ଍ client := &http.Client{} req, _ := http.NewRequest("GET", url, nil)

    res, err := client.Do(req.WithContext(ctx)) // ϦΫΤετ͸͜͜ͰԿΛ࣮ߦ͍ͯ͠Δʁ ※req.WithContext͸ʮݱࡏͷϦΫΤετʯͱʮ౉͞ΕͨcontextʯΛ૊Έ߹Θͤͨ৽͍͠http.RequestΛ ฦΓ஋ͱͯ͠ฦ͢ɻ͜ͷ࢓૊ΈʹΑͬͯɺcontextͷcancelΛhttp.Requestʹ఻͑Δ͜ͱ͕Մೳͱͳ͍ͬͯ Δɻ
  6. ͜͏͍͏ίʔυɺݟͨ͜ͱ͋Γ·ͤΜ͔ʁʢճ໨ʣ func AttachContextWithUser(ctx context.Context, user string) context.Context { return context.WithValue(ctx,

    "user", user) } func GetUserFromContext(ctx context.Context) (string, bool) { user, ok := ctx.Value("user").(string) return user, ok } func main() { ctx := AttachContextWithUser(context.Background(), "my name") user, _ := GetUserFromContext(ctx) fmt.Println(user) // my name }
  7. $POUFYUͷΠϯλϑΣʔεʢ࠶ܝʣ type Context interface { // …தུ // key:valueͰอ͍࣋ͯ͠Δ஋Λฦ͢ Value(key

    interface{}) interface{} } ※Contextʹ͸ఀࢭॲཧҎ֎ʹɺkey-valueܗࣜͰ஋Λอ࣋͢ΔೖΕ෺͕͋Γ·͢ɻ WebΞϓϦΛ࡞ΔࡍɺϦΫΤετͷத਎ʢϦΫΤετϔομʔ౳ʣΛcontext͔Βऔಘ͢Δͷ͸Α͋͘Δύλʔϯɻ ͭ·ΓɺWebΞϓϦʹ͓͍ͯcontext͸ʮϦΫΤετͷ஋͕֨ೲ͞ΕΔ৔ॴʯͱදݱͰ͖·͢ɻ ϩδοΫʹඞཁͳϝλσʔλΛ อ࣋͢Δ࢓૊Έ͕7BMVF
  8. ࢀߟࢿྉ w ެࣜυΩϡϝϯτ w IUUQTQLHHPEFWDPOUFYU w ʰ(P$VSSFODZ1BUUFSOT$POUFYUʱ w IUUQTHPEFWCMPHDPOUFYU w

    ʰվగ൛ΈΜͳͷ(Pݴޠʱ w IUUQTHJIZPKQCPPL w ʰ-FBSOJOH(P"O*EJPNBUJD"QQSPBDIUP3FBM8PSME(P1SPHSBNNJOHʱ w IUUQTXXXBNB[PODPKQEQ