rahjoo

package module
v1.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2025 License: MIT Imports: 4 Imported by: 3

README

Introduction

Go Reference

Rahjoo(رهـجـو) meaning Pathfinder in persian, is a lightweight zero dependency HTTP router library for Go, designed to work seamlessly with the standard net/http library. This library allows you to define routes with HTTP methods, group routes under common prefixes, and apply middlewares to handlers.

Features

  • HTTP Method Routing: Define routes for specific HTTP methods (e.g., GET, POST).
  • Route Grouping: Group routes under common prefixes (e.g., /api/v1).
  • Middleware Support: Apply middlewares to individual handlers or groups of routes.
  • Compatibility: Works with the standard http.ServeMux for easy integration.
  • Lightweight: Minimal dependencies and easy to use.

Installation

To install the library, use go get:

go get github.com/amirzayi/rahjoo

Example

package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	chim "github.com/go-chi/chi/v5/middleware"

	"github.com/amirzayi/rahjoo"
	"github.com/amirzayi/rahjoo/middleware"
	"github.com/amirzayi/rahjoo/middleware/cors"
)

func h(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, World!")
}

func listUsers(w http.ResponseWriter, r *http.Request) {}

func main() {
	mux := http.NewServeMux()

	mux.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./images"))))

	postUsersRoute := rahjoo.Route{
		"/posts/{id}/users": {
			http.MethodGet: rahjoo.NewHandler(listUsers, chim.NoCache, chim.RequestID),
		},
	}

	userV1Gp := rahjoo.NewGroupRoute("/api/v1/users", rahjoo.Route{
		"/list": {
			http.MethodGet: rahjoo.NewHandler(listUsers, middleware.EnforceJSON),
		},
		"/{id}": {
			http.MethodGet: rahjoo.NewHandler(http.NotFound),
		},
	}).SetMiddleware(chim.NoCache, chim.CleanPath)

	// empty method will route all method on given handler
	userV2Gp := rahjoo.NewGroupRoute("/api/v2", rahjoo.Route{
		"/users": {
			"": rahjoo.NewHandler(listUsers, chim.Throttle(6)),
		},
	}).SetMiddleware(middleware.EnforceJSON, chim.NoCache)

	// bind routes to http multiplexer
	rahjoo.BindRoutesToMux(mux, userV1Gp, userV2Gp, postUsersRoute)

	// you can use middleware developed based on std http.HttpHandler
	// such as chi router middlewares
	handler := middleware.Chain(mux,
		cors.CORSHandler(),
		middleware.Recovery(log.Default()),
		chim.Timeout(time.Second),
		chim.Logger,
		chim.RealIP)

	log.Fatal(http.ListenAndServe(":8080", handler))
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Documentation

Overview

Package rahjoo provides a flexible and lightweight routing solution for the standard library's `http.ServeMux`. It allows you to define routes with HTTP methods, group routes under common prefixes, and apply middlewares to handlers. The package is designed to work seamlessly with the standard `net/http` library, making it easy to integrate into existing projects.

Key Features: - Define routes with HTTP methods (e.g., GET, POST). - Group routes under common prefixes (e.g., "/api/v1"). - Apply middlewares to individual handlers or groups of routes. - Combine multiple route groups into a single routing table. - Bind routes to the standard `http.ServeMux` for compatibility with the `net/http` library.

Example Usage:

// Define a handler function
helloHandler := func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
}

// Create a GroupRoute with a prefix
group := router.GroupRoute{
    "/api/v1": router.Route{
        "/hello": {
            http.MethodGet: router.NewHandler(helloHandler, middleware.Recovery),
        },
    },
}

// Convert the GroupRoute to a Route
routes := router.NewGroup(group)

// Bind the routes to the ServeMux
mux := http.NewServeMux()
router.BindRoutesToMux(mux, routes)

// Start the HTTP server
http.ListenAndServe(":8080", mux)

For more details, see the documentation for individual types and functions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindRoutesToMux

func BindRoutesToMux(mux *http.ServeMux, routes ...Route)

BindRoutesToMux binds the provided routes to a http.ServeMux. It iterates over the routes, applies the middlewares to each handler using middleware.Chain, and registers the handlers with the ServeMux. The route paths are combined with their HTTP methods to create unique route identifiers (e.g., "GET /api/v1/books").

Example
package main

import (
	"log"
	"net/http"

	"github.com/amirzayi/rahjoo"
	"github.com/amirzayi/rahjoo/middleware"
)

func main() {
	listUsers := func(http.ResponseWriter, *http.Request) {}

	userV1Gp := rahjoo.NewGroupRoute("/api/v1/users", rahjoo.Route{
		"/list": {
			http.MethodGet: rahjoo.NewHandler(listUsers, middleware.EnforceJSON),
		},
		"/{id}": {
			http.MethodGet: rahjoo.NewHandler(http.NotFound),
		},
	})

	userV2Gp := rahjoo.NewGroupRoute("/api/v2", rahjoo.Route{
		"/users": {
			"": rahjoo.NewHandler(listUsers),
		},
	}).SetMiddleware(middleware.EnforceJSON, middleware.Recovery(log.Default()))

	mux := http.NewServeMux()
	mux.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./images"))))
	rahjoo.BindRoutesToMux(mux, userV1Gp, userV2Gp)
}

func NewHandler

func NewHandler(handler http.HandlerFunc, middlewares ...middleware.Middleware) actionHandler

NewHandler creates an actionHandler with the given HTTP handler and middlewares. The middlewares are applied in reverse order, meaning the last middleware in the list will be executed first (closest to the handler).

Example
package main

import (
	"log"
	"net/http"

	"github.com/amirzayi/rahjoo"
	"github.com/amirzayi/rahjoo/middleware"
)

func main() {
	h := func(w http.ResponseWriter, r *http.Request) {}

	rahjoo.NewHandler(h, middleware.EnforceJSON, middleware.Recovery(log.Default()))
}

Types

type Method

type Method string

Method represents the HTTP method for a request (e.g., http.MethodGet, http.MethodPost). If left empty, it will handle all HTTP methods for the given path.

type Path

type Path string

Path represents the URL path for a route (e.g., "/shelves/{shelf_id}/books"). It is used to define the endpoint for an HTTP request.

type Route

type Route map[Path]map[Method]actionHandler

Route defines a mapping of URL paths to their corresponding HTTP methods and handlers. It is a map where: - The key is a Path (URL path). - The value is another map where: - The key is a Method (HTTP method). - The value is an actionHandler(function to handle the request). This structure allows for flexible route definitions with support for multiple HTTP methods per path.

func MergeRoutes added in v1.2.3

func MergeRoutes(routes ...Route) Route

MergeRoutes combines multiple Route maps into a single Route map. It iterates over each Route and merges them into a single map, ensuring that routes with the same path and method are not overwritten.

func NewGroupRoute added in v1.2.0

func NewGroupRoute(prefix string, routes ...Route) Route

NewGroupRoute creates a new Group Route with prefix(e.g., "/api/v1").

Example
package main

import (
	"log"
	"net/http"

	"github.com/amirzayi/rahjoo"
	"github.com/amirzayi/rahjoo/middleware"
)

func main() {
	listUsers := func(http.ResponseWriter, *http.Request) {}

	_ = rahjoo.NewGroupRoute("/api/v1", rahjoo.Route{
		"/users": {
			http.MethodGet: rahjoo.NewHandler(listUsers),
		},
		"/post/{id}/users": {
			http.MethodGet: rahjoo.NewHandler(listUsers, middleware.Recovery(log.Default())),
		},
	}).SetMiddleware(middleware.EnforceJSON)
}

func (Route) SetMiddleware added in v1.2.0

func (r Route) SetMiddleware(middlewares ...middleware.Middleware) Route

SetMiddleware set some middlewares on route.

Directories

Path Synopsis
Package middleware provides HTTP middlewares.
Package middleware provides HTTP middlewares.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL