main.go
package main import ( "fmt" "log" "net/http" ) func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s\n", r.Method, r.URL.Path) next.ServeHTTP(w, r) }) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, with middleware!") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", helloHandler) server := &http.Server{ Addr: ":8080", Handler: loggingMiddleware(mux), } log.Println("Starting server on :8080...") if err := server.ListenAndServe(); err != nil { log.Fatal(err) } }
标签:Web,http,log,mux,golang,Handler,func,服务器,main From: https://www.cnblogs.com/boye169/p/18318300