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

実践 net/http Middleware パターン / Kizuku.go Vol.1

実践 net/http Middleware パターン / Kizuku.go Vol.1

Ken’ichiro Oyama

July 26, 2024
Tweet

More Decks by Ken’ichiro Oyama

Other Decks in Technology

Transcript

  1. • net/http ύοέʔδ • Package http provides HTTP client and

    server implementations. • HTTPΫϥΠΞϯτ΍HTTPαʔόͷ࣮૷ͷͨΊͷύοέʔδ • net/http ύοέʔδʹ͓͚Δ Middleware ύλʔϯ • HTTPϦΫΤετ/ϨεϙϯεΛऔΓѻ͏HTTPαʔόʹ͓͍ͯػೳΛ࣮૷͢Δࡍʹ࢖༻Ͱ͖ Δ࣮૷ύλʔϯ 6 net/http ύοέʔδʹ͓͚Δ Middleware ύλʔϯ net/http ύοέʔδʹ͓͚Δ Middleware ύλʔϯͱ͸Կ͔
  2. • ʢதུʣ The process of wrapping the Pylons application in

    middleware results in a structure conceptually similar to the layers in an onionʢλϚωΪʣ. • ຊηογϣϯʹ͓͚ΔMiddlewareύλʔϯͱಉ͡ • WSGI Middleware ͸ HTTPαʔόͱWebΞϓϦέ
 ʔγϣϯ/ϑϨʔϜϫʔΫͷதؒͷWSGIϨΠϠͰ࣮ݱ • ͪͳΈʹɺHTTPαʔόͷϨΠϠͰ΋WebΞϓϦέʔγϣϯ/
 ϑϨʔϜϫʔΫͷϨΠϠͰ΋Middlewareύλʔϯ͸͋Δ
 ʢ͋ͬͯΑ͍ʣ 9 net/http ύοέʔδʹ͓͚Δ Middleware ύλʔϯ WSGI Middleware https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/concepts.html#wsgi-middleware
  3. • ΞΫηεϩά • CORS • ೝূೝՄ • ΞΫηε੍ޚ 21 Α͘࢖ΘΕΔ

    Middleware ύλʔϯΛར༻ͨ͠ػೳ Α͘࢖ΘΕΔ Middleware ύλʔϯΛར༻ͨ͠ػೳ
  4. • rc is a response cache middleware for cache. •

    ϦΫΤετʹԠͯ͡ಈతʹΩϟογϡ൑ఆΛม͑Δ͜ͱ͕Ͱ͖ΔMiddleware • Ωϟογϡ൑ఆ΍Ωϟογϡͷฦ٫͸ rc.Casher ΠϯλʔϑΣʔεΛຬ࣮ͨ͢૷Λ࡞Δ͜ ͱͰ೚ҙͷ൑ఆϩδοΫΛ૊ΈࠐΉ͜ͱ͕Մೳ • ΩϟογϡετϨʔδ΋ಠࣗʹ૊ΈࠐΈՄೳ • σΟεΫΩϟογϡͰ͋Ε͹ɹɹhttps://github.com/2manymws/rcutil Λ࢖༻Մೳ • Ωϟογϡૢ࡞ʹ͓͚ΔσϑΥϧτͷಈ࡞͸RFC9111ʹ४ڌ • ϓϩΩγαʔόʹඞཁͳػೳͷΈΛ࣮૷͍ͯ͠Δ 26 զʑ͕࣮ફ͍ͯ͠Δ Middleware ύλʔϯΛར༻ͨ͠ػೳ https://github.com/2manymws/rc
  5. • rl is a rate limit middleware for multiple limit

    rules. • ϦΫΤετʹԠͯ͡ಈతʹϨʔτϦϛοτͷϧʔϧΛઃఆͰ͖ΔMiddleware • ϨʔτϦϛοτͷϧʔϧΛ rl.Limitter ΠϯλʔϑΣʔεΛຬͨ͢͜ͱͰ૊ΈࠐΉ͜ͱ͕Ͱ͖ Δɻ • ϨʔτϦϛοτͷϩδοΫʹ͸Sliding Window CounterύλʔϯΛ࠾༻ • https://blog.cloudflare.com/counting-things-a-lot-of-different-things/ • IPϕʔε΍ϗετϕʔεͳͲ࣮ફతͳϦϛοτϧʔϧ͸ http://github.com/2manymws/rlutils ʹޙ չ͍ͯ͠Δ 28 զʑ͕࣮ફ͍ͯ͠Δ Middleware ύλʔϯΛར༻ͨ͠ػೳ https://github.com/2manymws/rl
  6. • mm is a middleware-middleware for multiple rules. • ϦΫΤετʹԠͯ͡ಈతʹMiddlewareΛ੾Γସ͑Δ͜ͱ͕Ͱ͖ΔMiddleware

    • Middlewareద༻ϧʔϧΛ mm.Builder ΠϯλʔϑΣʔεΛຬͨ͢͜ͱͰ૊ΈࠐΉ͜ͱ͕Ͱ͖ Δɻ • ·࣮ͩફ౤ೖ͸͍ͯ͠ͳ͍ • ར༻͍ͨ͠Middleware͕ϦΫΤετʹԠͯ͡੾Γସ͑Δͱ͍͏ػೳΛ࣋ͨͳ͍৔߹ͳͲʹ࢖༻ ͢ΔΠϝʔδ 30 զʑ͕࣮ફ͍ͯ͠Δ Middleware ύλʔϯΛར༻ͨ͠ػೳ https://github.com/2manymws/mm
  7. 32 ·ͱΊ શͯ͸http.Handler • net/httpύοέʔδͷHTTPαʔό͸http.HandlerΛऔΓѻ͏ • http.ServeMux΋http.Handler • WebΞϓϦέʔγϣϯʹ͓͚Δʮϧʔλʯͱݺ͹ΕΔ΋ͷ͸ɺ୯ʹʮϦΫΤετύεΛݩʹಈతʹ http.HandlerΛ੾Γ͔͑Δhttp.Handlerʯͱݴ͑Δ

    • Middleware΋http.Handler • શͯͷϦΫΤετ/Ϩεϙϯεʹରͯ͠λϚωΪͷΑ͏ʹhttp.HanderΛϥοϓ͍ͯ͠Δ • Middlewareͷڍಈ΋ϦΫΤετΛݩʹಈతʹมΘ͍͍ͬͯ • Α͏͸ʮػೳશମΛͲ͏σβΠϯ͢Δ͔ʯʹམͪண͘ • શͯ͸http.Handler