Created
June 29, 2022 13:14
-
-
Save rafaelsq/9a89d555e1468872cb680d5a0908f7b0 to your computer and use it in GitHub Desktop.
httprouter easy middlewares
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
func main() { | |
router := httprouter.New() | |
r := Middlewares{router: router} | |
r.Use(func(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("First Middleware") | |
next.ServeHTTP(w, r) | |
}) | |
}) | |
r.Get("/", website.Handle) | |
r = *r.UseNew(func(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("Second Middleware") | |
next.ServeHTTP(w, r) | |
}) | |
}) | |
r.Route("/b", func(r *Middlewares) { | |
// Post: /b/c | |
r.Post("/c", website.Handle) | |
}) | |
srv := http.Server{Addr: ":8080", Handler: router} | |
srv.ListenAndServe() | |
} |
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
type Router struct { | |
router *httprouter.Router | |
middlewares []func(next http.Handler) http.Handler | |
prefix string | |
} | |
func (m *Router) Use(fn func(next http.Handler) http.Handler) { | |
m.middlewares = append(m.middlewares, fn) | |
} | |
func (m Router) UseNew(fn func(next http.Handler) http.Handler) *Router { | |
m.middlewares = append(m.middlewares, fn) | |
return &m | |
} | |
func (m Router) H(fn http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
var f http.Handler = fn | |
for i := len(m.middlewares) - 1; i >= 0; i-- { | |
f = m.middlewares[i](f) | |
} | |
f.ServeHTTP(w, r) | |
} | |
} | |
func (m *Router) Get(path string, fn http.HandlerFunc) { | |
m.router.HandlerFunc(http.MethodGet, m.prefix+path, m.H(fn)) | |
} | |
func (m *Router) Post(path string, fn http.HandlerFunc) { | |
m.router.HandlerFunc(http.MethodPost, m.prefix+path, m.H(fn)) | |
} | |
func (m *Router) Put(path string, fn http.HandlerFunc) { | |
m.router.HandlerFunc(http.MethodPut, m.prefix+path, m.H(fn)) | |
} | |
func (m *Router) Delete(path string, fn http.HandlerFunc) { | |
m.router.HandlerFunc(http.MethodDelete, m.prefix+path, m.H(fn)) | |
} | |
func (m Router) Route(path string, fn func(r *Router)) { | |
m.prefix += path | |
fn(&m) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment