0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go言語ミドルウェア例

Last updated at Posted at 2023-01-31

やりたいこと
動的に2つのミドルウェアメソッドを呼んでから最後に対象ハンドラーを呼べるようにします。
 ・middleware2⇒middleware1⇒handler

サンプル

// main.go
package main

import "fmt"

type handlerFunc func(interface{})
type middlewareFunc func(interface{}, handlerFunc)

func main() {
	middlewares := []middlewareFunc{middleware1(), middleware2()}
	c := chainHandler(middlewares)
	c("テスト", handler())

}

func handler() handlerFunc {
	return func(param interface{}) {
		fmt.Println("handler1")
		fmt.Println(param)
	}
}

func middleware1() middlewareFunc {
	return func(param interface{}, handler handlerFunc) {
		fmt.Println("middleware1")
		handler(param)
	}
}

func middleware2() middlewareFunc {
	return func(param interface{}, handler handlerFunc) {
		fmt.Println("middleware2")
		handler(param)
	}
}

func chainHandler(middlewares []middlewareFunc) middlewareFunc {
	return func(reqParam interface{}, handler handlerFunc) {

		chain := func(middleware middlewareFunc, handler handlerFunc) handlerFunc {
			return func(param interface{}) {
				middleware(param, handler)
			}
		}

		h := handler
		for i := len(middlewares) - 1; i >= 0; i-- {
			h = chain(middlewares[i], h)
		}
		h(reqParam)
	}
}

main実行結果
middleware1
middleware2
handler1
テスト

ポイント
middlewareFuncをラップするメソッドのI/FをhandlerFuncと同じにする。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?