Code on closures - got it from a book but the explanation wasn't clear

package main

import (
“fmt”
“net/http”
)

func testHandlerFunc(w http.ResponseWriter, r *http.Request) {
fmt.Println(“Printing from testHandlerFunc”)
w.Write([]byte(“From testHandlerFunc\n”))
}

func middleware(handler http.Handler) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

	fmt.Println("Executing before request phase")

	testHandlerFunc(w, r)  // What is this doing?

	handler.ServeHTTP(w, r)

	fmt.Println("Executing after response phase")
})

}

func mainLogic(w http.ResponseWriter, r *http.Request) {
fmt.Println(“Executing mainLogic”)
w.Write([]byte(“OK”))
}

func main() {

mainLogicHandler := http.HandlerFunc(mainLogic)  // I don't fully understand why you're putting "mainLogic" into a http.HandlerFunc() type
http.Handle("/", middleware(mainLogicHandler))  // I understand this

}

*** sorry I can’t seem to get the code formatting to work ***

So this code works, and I understand the point of wanting to use closures. You can use functions to chain various pieces of code together. I kind of get what’s going on, but the book doesn’t explain it very well. I know this is a very open ended question, I’m just trying to wrap my head around this.

Kind regards,
Steven

package main

import (
“fmt”
“net/http”
)

func testHandlerFunc(w http.ResponseWriter, r *http.Request) {
fmt.Println(“Printing from testHandlerFunc”)
w.Write([]byte(“From testHandlerFunc\n”))
}

func middleware(handler http.Handler) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

	fmt.Println("Executing before request phase")

	testHandlerFunc(w, r)  // What is this doing?  
//This is calling the testHandlerFunc defined above with the http.ResponseWriter and http.Request 
//of the present function scope, this handler's parameters. 

	handler.ServeHTTP(w, r)

	fmt.Println("Executing after response phase")
})
}

func mainLogic(w http.ResponseWriter, r *http.Request) {
fmt.Println(“Executing mainLogic”)
w.Write([]byte(“OK”))
}

func main() {

mainLogicHandler := http.HandlerFunc(mainLogic)  // I don't fully understand why you're putting "mainLogic" into a http.HandlerFunc() type
//This isn't a type its a function call that returns a HandlerFunc, it gives your basic interface definition function
// the extra methods it needs to actually be a HandlerFunc, such as ServeHTTP
http.Handle("/", middleware(mainLogicHandler))  // I understand this
}

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.