谷歌云功能中的中间件处理程序有什么等价物?
在标准方法中,通常我会这样做:
router.Handle("/receive", middlewares.ErrorHandler(MyReceiveHandler))
然后,在中间件中:
type ErrorHandler func(http.ResponseWriter, *http.Request) error
func (fn ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := fn(w, r)
if err == nil {
return
}
log.Printf("An error accured: %v", err)
clientError, ok := err.(errors.BaseError)
if !ok {
w.WriteHeader(500)
return
}
w.WriteHeader(clientError.GetStatusCode())
w.Write([]byte(clientError.Error()))
}
在AWS Lambda中,我可以使用(例如(实现相同的功能
func main() {
lambda.Start(
middlewares.Authentication(Handler),
)
}
但我在GCP函数中找不到这样做的方法。它是如何工作的?
你能帮我吗?
假设您在开发环境中从以下服务器代码开始:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.Handle("/", MiddlewareFinalMsg(" Goodbye!", http.HandlerFunc(HelloWorld)))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func MiddlewareFinalMsg(msg string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
fmt.Fprint(w, msg)
})
}
func HelloWorld(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "Hello, World!")
}
据我所知,GCF要求其入口点是类型为func(http.ResponseWriter, *http.Request)
的导出标识符(不是http.HandlerFunc
,也不是http.Handler
(;因此,如果您有一个http.Handler
,您需要显式地选择它的ServeHTTP
方法来获得期望类型的函数。但是,该标识符可以是包级别的函数、方法或变量。
以下是如何为GCF:调整上面的代码
package p
import (
"fmt"
"net/http"
)
// use F as your GCF's entry point
var F = MiddlewareFinalMsg(" Goodbye!", http.HandlerFunc(HelloWorld)).ServeHTTP
func MiddlewareFinalMsg(msg string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
fmt.Fprint(w, msg)
})
}
func HelloWorld(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "Hello, World!")
}