【问题标题】:What means foo()(bar) in go and how it works?go 中的 foo()(bar) 是什么意思,它是如何工作的?
【发布时间】:2022-12-10 01:02:14
【问题描述】:

在auth0 Golang 快速入门教程中,我找到了这段代码:

router.Handle("/api/private", middleware.EnsureValidToken()(
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"message":"Hello from a private endpoint! You need to be authenticated to see this."}`))
    }),
 ))

然后我将它简化为这种形式:

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write([]byte(`{"message":"Hello from test"}`))
}

func preHandler() func(next http.Handler) http.Handler {

    log.Println("in preHandler")
    return func(next http.Handler) http.Handler {
        return check(next)
    }
}

func main() {
    http.Handle("/test/", preHandler()(http.HandlerFunc(handler)))
    http.ListenAndServe(":80", nil)
}

但是我不知道这段代码是如何工作的以及它的含义是什么preHandler()(http.HandlerFunc(handler))

感谢帮助!

附言 我试图在谷歌中找到答案,但一无所获。我只是想知道它是如何工作的

【问题讨论】:

    标签: go syntax semantics


    【解决方案1】:

    该声明

    http.Handle("/test/", preHandler()(http.HandlerFunc(handler)))
    

    有四个function calls。我将通过将一个语句分成四个语句来解释发生了什么:

    f := preHandler() // f is function with type func(next http.Handler) http.Handler
    h := http.HandlerFunc(handler) // h is an http.Handler
    hw := f(h)   // call f with h, result is an http.Handler
    http.Handle("/test/", hw)  // register the handler
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多