Go HTTP request multiplexer.
example | ||
middleware | ||
.gitignore | ||
go.mod | ||
LICENSE | ||
README.md | ||
resource.go | ||
router_serve.go | ||
router.go |
Mux
Tiny wrapper around Go's builtin http.ServeMux with easy routing methods.
Example
package main
import (
"log/slog"
"net/http"
"gitserver.in/patialtech/mux"
)
func main() {
// create a new router
r := mux.NewRouter()
// you can use any middleware that is: "func(http.Handler) http.Handler"
// so you can use any of it
// - https://github.com/gorilla/handlers
// - https://github.com/go-chi/chi/tree/master/middleware
// add some root level middlewares, these will apply to all routes after it
r.Use(middleware1, middleware2)
// let's add a route
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("i am route /hello"))
})
// r.Post(pattern string, h http.HandlerFunc)
// r.Put(pattern string, h http.HandlerFunc)
// ...
// you can inline middleware(s) to a route
r.
With(mwInline).
Get("/hello-2", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("i am route /hello-2 with my own middleware"))
})
// define a resource
r.Resource("/photos", func(resource *mux.Resource) {
// rails style resource routes
// GET /photos
// GET /photos/new
// POST /photos
// GET /photos/:id
// GET /photos/:id/edit
// PUT /photos/:id
// PATCH /photos/:id
// DELETE /photos/:id
resource.Index(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("all photos"))
})
resource.New(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("upload a new pohoto"))
})
})
// create a group of few routes with their own middlewares
r.Group(func(grp *mux.Router) {
grp.Use(mwGroup)
grp.Get("/group", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("i am route /group"))
})
})
// catches all
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello there"))
})
// Serve allows graceful shutdown, you can use it
r.Serve(func(srv *http.Server) error {
srv.Addr = ":3001"
// srv.ReadTimeout = time.Minute
// srv.WriteTimeout = time.Minute
slog.Info("listening on http://localhost" + srv.Addr)
return srv.ListenAndServe()
})
}
func middleware1(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("i am middleware 1")
h.ServeHTTP(w, r)
})
}
func middleware2(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("i am middleware 2")
h.ServeHTTP(w, r)
})
}
func mwInline(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("i am inline middleware")
h.ServeHTTP(w, r)
})
}
func mwGroup(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("i am group middleware")
h.ServeHTTP(w, r)
})
}