mux/README.md
2024-10-12 19:34:17 +05:30

2.6 KiB

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() {
	// init mux router
	r := mux.NewRouter()

	// here is how can add 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("hello1"))
	})
	// 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("/test", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("middle ware 3 test"))
		})

	// you define a resource
	r.Resource("/photos", func(resource *mux.Resource) {
		// rails style 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("user index"))
		})

		resource.New(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("create new user"))
		})
	})

	// you can create 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 group 1"))
		})
	})

	// catche all
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello there"))
	})

	// Serve allows graceful shutdown
	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()
	})
}

//
// example middlewares
//
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)
	})
}