运行 Gorilla mux 处理后的中间件

Run middleware after Gorilla mux handling

我正在尝试使用 Golang 中间件 运行 处理 Gorilla Mux 路由之后,以更改每个请求的响应。

代码示例见下文。目前它 returns 'run before, run test',目标是 return 'run before, run test, run after' 使用 运行safter 中间件。

Gorilla Mux 可以实现这样的功能吗?

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
)

func runsbefore(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("run before, "))
        h.ServeHTTP(w, r)
    }

    return http.HandlerFunc(fn)
}

func runsafter(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("run after, "))
        h.ServeHTTP(w, r)
    }

    return http.HandlerFunc(fn)
}

func runtest(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("run test, "))
}

func main() {
    fmt.Println("Server starting on port 8000")
    r := mux.NewRouter()
    r.HandleFunc("/", runtest).Methods("GET")
    http.ListenAndServe(":8000", runsbefore(r))
    // something like: http.ListenAndServe(":8000", runsbefore(r(runsafter)))
}

使用

http.ListenAndServe(":8000", runsAfter(runsbefore(r)))

并修复 runsAfter 中的错误:

func runsafter(h http.Handler) http.Handler {
  fn := func(w http.ResponseWriter, r *http.Request) {
    h.ServeHTTP(w, r)
    w.Write([]byte("run after, "))
  }

  return http.HandlerFunc(fn)
}