2
votes

I'm trying to use Golang middleware to run after handling Gorilla Mux routing, in order to change the response of each request.

Code sample see below. Currently it returns 'run before, run test', goal is to return 'run before, run test, run after' using the runsafter middleware.

Is something like this possible with 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)))
}
1

1 Answers

2
votes

Use

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

and fix the error in 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)
}