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?

[備忘録] Go CloudFunctionsでChain Middlewareを利用する

Posted at

Go CloudFunctionsでChain Middlewareを利用する

経緯

フト思った時に変態っぽいコードの書き方をしていたので、備忘録。

TL;DR

呼び出し元のfunctionsで、http.HandlerFunc(handler).ServeHttp(w, r)で実施する。

middleware.go
package middleware

import "net/http"

type Middleware func(http.Handler) http.Handler

func ChainMiddleware(h http.Handler, m ...Middleware) http.Handler {
	if len(m) < 1 {
		return h
	}

	wrapped := h

	for i := len(m) - 1; i >= 0; i-- {
		wrapped = m[i](wrapped)
	}

	return wrapped
}

func LoggerMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		slog.Info("call http")
		next.ServeHTTP(w, r)
	})
}

function.go
package function

func init() {
  ms := []middleware.Middleware{
		middleware.LoggerMiddleware,
	}
	funcframework.RegisterHTTPFunction(functionName,
		func(w http.ResponseWriter, r *http.Request) {
			middleware.ChainMiddleware(http.HandlerFunc(HelloHandler), ms...).ServeHTTP(w, r)
		},
	)

}
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?