In restful services, it is usually necessary to record request information into logs. The following example shows how go implements a simple logging middleware.
Its basic principle is to foo/bar
pass the business function (in this example) as a parameter to the log function (in this example logging
), and then pass the log function as a parameter http.HandleFunc
.
package main
import (
"fmt"
"log"
"net/http"
)
func logging(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
f(w, r)
}
}
func foo(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
http.HandleFunc("/foo", logging(foo))
http.HandleFunc("/bar", logging(bar))
http.ListenAndServe(":8080", nil)
}
Every time you visit http://localhost:8080/foo
or http://localhost:8080/bar
, the background will record the requested address
2021/02/28 23:56:41 /bar
2021/02/28 23:56:48 /foo