Mozzart
Mozzart

Reputation: 1

What means foo()(bar) in go and how it works?

In auth0 QuickStart tutorial for Golang I had found this piece of code:

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."}`))
    }),
 ))

Then I had simplify it to this form:

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

But I can't figure out how is working and what is meaning of this piece of code preHandler()(http.HandlerFunc(handler))

Thnx for help!

P.s. I tried to find answer in google but nothing. I just want to find out how it works

Upvotes: 0

Views: 173

Answers (1)

moriss
moriss

Reputation: 116

The statement

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

has three function calls and a type conversion. I'll explain what's going on by splitting the one statement into four statements:

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

Upvotes: 3

Related Questions