Last active
June 20, 2019 10:57
-
-
Save miquelbar/a89d066ecb1a564a6db9a83284115097 to your computer and use it in GitHub Desktop.
middlewareManage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With trilopin fixes | |
package main | |
import "fmt" | |
import "net/http" | |
import "log" | |
type Middleware func(http.Handler) http.Handler | |
type MiddlewareManager struct { | |
ms []Middleware | |
} | |
func (mm *MiddlewareManager) Compose(m ...Middleware) { | |
mm.ms = append(mm.ms, m...) | |
} | |
func (mm *MiddlewareManager) DoMiddle(h http.Handler) http.Handler { | |
for _, m := range mm.ms { | |
h = m(h) | |
} | |
return h | |
} | |
func logger(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("%s requested %s", r.RemoteAddr, r.URL) | |
h.ServeHTTP(w, r) | |
}) | |
} | |
func test(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("test function %s", r.URL) | |
h.ServeHTTP(w, r) | |
}) | |
} | |
func main() { | |
mm := MiddlewareManager{} | |
mm.Compose(logger, test) | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintln(w, "Are you here?") | |
}) | |
mmux := mm.DoMiddle(mux) | |
err := http.ListenAndServe(":9999", mmux) | |
log.Fatal(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment