http middleware

tags: learning go programming

content

  • a middleware is a function that takes in a function of a type, does something, calls the function, and returns another function of the same type

  • http middleware

func loggingMiddleware(next http.Handler) http.Handler {
	// create a function
	myFunc := func(w http.ResponseWriter, r *http.Request) {
		log.Println("middleware")
		next.ServeHTTP(w, r)
	}
	// http.HandlerFunc converts myFunc to http.Handler
	handlerFunc := http.HandlerFunc(myFunc)
	return handlerFunc
}
  • Go’s idiomatic way:
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWrite, r *http.Request) {
		log.Println("middleware")
		next.ServeHTTP(w, r)
		}
	)
}

up

down

reference