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

Contextアンチパターン

 Contextアンチパターン

golang.tokyo#5でのLT資料です。

Seiji Takahashi

April 27, 2017
Tweet

More Decks by Seiji Takahashi

Other Decks in Programming

Transcript

  1. ࣗݾ঺հ • twitter: @__timakin__ • github: timakin • גࣜձࣾGunosy ৽نࣄۀ։ൃࣨ(Go/Swift)

    • ओͳGoϥΠϒϥϦ։ൃ෺ • gopli (DBϨϓϦέʔγϣϯπʔϧ) • gonvert (จࣈίʔυม׵ϥΠϒϥϦ) • octop (githubͷissue, PRϏϡʔ༻CLIπʔϧ) • ts (ٕज़ɾϏδωεܥχϡʔε८ճCLIπʔϧ) • ϓϥΠϕʔτͰΫϩʔϥʔ࡞੒ɺ࠷ۙಈը഑৴पΓ͕ؾʹͳͬͯ·͢ɻ
  2. Copyright© Gunosy Inc. All Rights Reserved 4 Go / Python

    ΤϯδχΞืूத ▶https://gunosy.co.jp/recruit/ Gunosy͸ɺ౦ژେֶʹ௨͏3ਓͷֶੜͷ
 ʮ৘ใΛੈքதͷਓʹ࠷దʹಧ͚͍ͨʯͱ͍͏૝͍͔Β࢝·Γ·ͨ͠ɻ ౦ূϚβʔζ্৔ɺ࿡ຊ໦ώϧζ΁ͷΦϑΟεҠసΛܦͯɺ
 େ͖͘੒௕͍ͯ͠ΔձࣾͰ׆༂͍ͨ͠ϝϯόʔΛืू͍ͯ͠·͢ɻ
  3. repository in context • ਃ͠։͖͍͟͝·ͤΜʂʂ̍̍
 ͍͕ͭ͜ਆͩʂ • ·͊ͿͬͪΌ͚طଘͷ࣮૷(or ࢿྉ)ࢀߟʹ
 ࡞ͬͨΜͰ͕͢ɺέʔεόΠέʔεͰɺ


    ΘΓͱ͜͏͍͏globalͳΦϒδΣΫτΛೖΕͯΔ
 ݹ͍࣮૷ͱ͔͋ͬͯɺਅࣅͪΌͬͨɻ • ඪ४ύοέʔδͱͯ͠૊Έࠐ·ΕΔલͷ࣮૷Ͱ͸
 ͜͏͍͏ͷ΋͋ͬͨΑɺ͋ͬͨ͸ͣͳΜͩɻ • ਖ਼௚repository͚ͩ͡Όͳ͘configͱ͔΋٧ΊͪΌͬͨ
  4. GoDoc • Package context defines the Context type, 
 which

    carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. • Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. • Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. • ͢·Μͯɻ
  5. GoDoc • ओʹgoroutine͕བྷΉॲཧɺAPIΛ·͙ͨॲཧΛߦ͏࣌ɺ
 λΠϜΞ΢τ੍ޚΛద੾ʹߦ͏ͨΊʹ࢖͏ • UserIDɺଞJWT౳ͷɺͦͷϦΫΤετʹݶఆ͞ΕΔ஋ΛGet/Set͢Δ ͱ͖ʹͷΈValueΛ࢖͏ • Go1.7Ҏલ(ࠓͷGAEͱ͔)
 func

    GetHandler(ctx context.Context, 
 w http.ResponseWriter, r *http.Request)
 
 Go1.7Ҏ߱
 ctx := r.Context() • ଞͷ༻్ɺड͚౉͠ํͰ࢖Θͳ͍ɻ
 ઈରͩͧɻ
  6. GoDoc • ແବʹߏ଄ମʹcontextೖΕͳ͍ • echo -> net/http • ContextΛద੾ʹϋϯυϥʹ౉͢ •

    λΠϜΞ΢τઃఆ͸ServeHTTPͰߦ͏ʢMiddlewareͰ΋Մʣ • func Handler(ctx context.Context, w http.ResponseWriter, r *http.Request) • request-scopedͳ஋ʹݶఆ • repository.FromContextͱ͔શ෦ফ͢ • ϋϯυϥͰ౎౓ctxΛ౉ͯ͠ੜ੒ • ֤छΫϥΠΞϯτ΍Βlogger͸HandlerͷϨγʔόΛఆٛͯͦ͠ͷதʹೖΕΔ • function (app *App) GetItemHandler(ctx context.Context, …)
  7. request-scopedͳ஋ʹݶఆ • ͔ͯrequest-scopedͳ஋ͱ͔ಛʹͳ͍APIͩͬͨɻ • ͳͷͰWithValueશ෦ফͨ͠ɻ • repository.FromContextͱ͔શ෦ফ͢ • ϋϯυϥͰ౎౓ctxΛ౉ͯ͠ੜ੒ •

    GAEͩͱloggerͱ͔datastoreͰcontext͕ඞཁ • ͳͷͰɺglobalʹѻ͍͍ͨ஋ͩͱͯ͠΋ɺ
 ϋϯυϥҎ߱Ͱຖճݺͼग़ͯ͠·͢ɻ
 ʢ͜Ε͸ϕετϓϥΫςΟε͋Δͷ͔ʁʣ
  8. • (app *App)ΛϨγʔόͱͯ͠ઃఆ͢Δʹ͸handlerʹ ౰ͨΔϝιου͸શͯಉҰpackageͱͯ͠ఆٛ͞ΕΔ ඞཁ͕͋Δ • cannot define new methods

    on non-local type • ͳͷͰɺݸผͷυϝΠϯϩδοΫΛ࣋ͭσΟϨΫτϦ ͱ͸ผʹɺhandlerσΟϨΫτϦΛஔ͖ɺͦ͜ʹApp ͷఆٛͱݸผͷϦΫΤετϋϯυϥΛ࣋ͨͤΔɻ Ϩγʔόʹglobalͳ஋ΛೖΕΔ