routegroup

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2024 License: MIT Imports: 2 Imported by: 22

README

routegroup Build Status Go Report Card Coverage Status godoc

routegroup is a tiny Go package providing a lightweight wrapper for efficient route grouping and middleware integration with the standard http.ServeMux.

Features

  • Simple and intuitive API for route grouping and route mounting.
  • Easy middleware integration for individual routes or groups of routes.
  • Seamless integration with Go's standard http.ServeMux.

Why One More Router?

Despite what the section title might suggest, routegroup is not another router. With Go's 1.22 release, the standard library's routing enhancements have made it possible to implement sophisticated routing logic without the need for external libraries. These enhancements provide the foundation for building fully functional HTTP servers directly with the tools Go offers.

However, while the standard http.ServeMux has become more powerful, it still lacks some conveniences, particularly in route grouping and middleware management. This is where routegroup steps in. Rather than reinventing the wheel, routegroup aims to supplement the existing routing capabilities by providing a minimalist abstraction layer for efficiently grouping routes and applying middleware to these groups.

Install and update

go get -u github.com/go-pkgz/routegroup

Usage

Creating a New Route Group

To start, create a new route group without a base path:

func main() {
    mux := http.NewServeMux()
    group := routegroup.New(mux)
}

Adding Routes with Middleware

Add routes to your group, optionally with middleware:

    group.Use(loggingMiddleware, corsMiddleware)
    group.Handle("/hello", helloHandler)
    group.Handle("/bye", byeHandler)

Creating a Nested Route Group

For routes under a specific path prefix Mount method can be used to create a nested group:

    apiGroup := routegroup.Mount(mux, "/api")
    apiGroup.Use(loggingMiddleware, corsMiddleware)
    apiGroup.Handle("/v1", apiV1Handler)
    apiGroup.Handle("/v2", apiV2Handler)

Complete Example

Here's a complete example demonstrating route grouping and middleware usage:

package main

import (
	"fmt"
	"net/http"
	
	"github.com/go-pkgz/routegroup"
)

func main() {
	mux := http.NewServeMux()
	apiGroup := routegroup.Mount(mux, "/api")

	// add middleware
	apiGroup.Use(loggingMiddleware, corsMiddleware)

	// route handling
	apiGroup.Handle("GET /hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, API!"))
	})
	
	// add another group with its own set of middlewares
	protectedGroup := apiGroup.Group()
	protectedGroup.Use(authMiddleware)
	protectedGroup.Handle("GET /protected", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Protected API!"))
    })

    http.ListenAndServe(":8080", mux)
}

Applying Middleware to Specific Routes

You can also apply middleware to specific routes inside the group without modifying the group's middleware stack:

apiGroup.With(corsMiddleware, helloHandler).Handle("GET /hello",helloHandler)

Alternative Usage with Route

You can also use the Route method to add routes and middleware in a single function call:

mux := http.NewServeMux()
group := routegroup.New(mux)
group.Route(b func(*routegroup.Bundle) {
    b.Use(loggingMiddleware, corsMiddleware)
    b.Handle("GET /hello", helloHandler)
    b.Handle("GET /bye", byeHandler)
})
http.ListenAndServe(":8080", mux)

Using derived groups

In some instances, it's practical to create an initial group that includes a set of middlewares, and then derive all other groups from it. This approach guarantees that every group incorporates a common set of middlewares as a foundation, allowing each to add its specific middlewares. To facilitate this scenario, routegroup offers both Bundle.Group and Bundle.Mount methods, and it also implements the http.Handler interface. The following example illustrates how to utilize derived groups:

// create a new bundle with a base set of middlewares
// note: the bundle is also http.Handler and can be passed to http.ListenAndServe
mux := routegroup.New(http.NewServeMux()) 
mux.Use(loggingMiddleware, corsMiddleware)

// add a new group with its own set of middlewares
// this group will inherit the middlewares from the base group
apiGroup := mux.Group()
apiGroup.Use(apiMiddleware)
apiGroup.Handle("GET /hello", helloHandler)
apiGroup.Handle("GET /bye", byeHandler)


// mount another group for the /admin path with its own set of middlewares, 
// using `Set` method to show the alternative usage.
// this group will inherit the middlewares from the base group as well
mux.Mount("/admin").Route(func(b *routegroup.Bundle) {
    b.Use(adminMiddleware)
    b.Handle("POST /do", doHandler)
})

// start the server, passing the wrapped mux as the handler
http.ListenAndServe(":8080", mux)

Contributing

Contributions to routegroup are welcome! Please submit a pull request or open an issue for any bugs or feature requests.

License

routegroup is available under the MIT license. See the LICENSE file for more info.

Documentation

Overview

Package routegroup provides a way to group routes and applies middleware to them. Works with the standard library's http.ServeMux.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

type Bundle struct {
	// contains filtered or unexported fields
}

Bundle represents a group of routes with associated middleware.

func Mount

func Mount(mux *http.ServeMux, basePath string) *Bundle

Mount creates a new group with a specified base path.

Example
package main

import (
	"net/http"

	"github.com/go-pkgz/routegroup"
)

func main() {
	mux := http.NewServeMux()
	group := routegroup.Mount(mux, "/api")

	// apply middleware to the group
	group.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Add("X-Test-Middleware", "true")
			next.ServeHTTP(w, r)
		})
	})

	// add test handlers
	group.Handle("GET /test", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	group.Handle("POST /test2", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	// start the server
	if err := http.ListenAndServe(":8080", mux); err != nil {
		panic(err)
	}
}

func New

func New(mux *http.ServeMux) *Bundle

New creates a new Group.

Example
package main

import (
	"net/http"

	"github.com/go-pkgz/routegroup"
)

func main() {
	mux := http.NewServeMux()
	group := routegroup.New(mux)

	// apply middleware to the group
	group.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Add("X-Mounted-Middleware", "true")
			next.ServeHTTP(w, r)
		})
	})

	// add test handlers
	group.Handle("GET /test", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	group.Handle("POST /test2", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	// start the server
	if err := http.ListenAndServe(":8080", mux); err != nil {
		panic(err)
	}
}

func (*Bundle) Group added in v0.2.0

func (b *Bundle) Group() *Bundle

Group creates a new group with the same middleware stack as the original on top of the existing bundle.

func (*Bundle) Handle

func (b *Bundle) Handle(path string, handler http.HandlerFunc)

Handle adds a new route to the Group's mux, applying all middlewares to the handler.

func (*Bundle) Mount added in v0.2.0

func (b *Bundle) Mount(basePath string) *Bundle

Mount creates a new group with a specified base path on top of the existing bundle.

func (*Bundle) Mux added in v0.3.0

func (b *Bundle) Mux() *http.ServeMux

Mux returns the underlying http.ServeMux

func (*Bundle) Route added in v0.2.0

func (b *Bundle) Route(configureFn func(*Bundle))

Route allows for configuring the Group inside the configureFn function.

Example
package main

import (
	"net/http"

	"github.com/go-pkgz/routegroup"
)

func main() {
	mux := http.NewServeMux()
	group := routegroup.New(mux)

	// configure the group using Set
	group.Route(func(g *routegroup.Bundle) {
		// apply middleware to the group
		g.Use(func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.Header().Add("X-Test-Middleware", "true")
				next.ServeHTTP(w, r)
			})
		})
		// add test handlers
		g.Handle("GET /test", func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(http.StatusOK)
		})
		g.Handle("POST /test2", func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(http.StatusOK)
		})
	})

	// start the server
	if err := http.ListenAndServe(":8080", mux); err != nil {
		panic(err)
	}
}

func (*Bundle) ServeHTTP added in v0.2.0

func (b *Bundle) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

func (*Bundle) Use

func (b *Bundle) Use(middleware func(http.Handler) http.Handler, more ...func(http.Handler) http.Handler)

Use adds middleware(s) to the Group.

func (*Bundle) With

func (b *Bundle) With(middleware func(http.Handler) http.Handler, more ...func(http.Handler) http.Handler) *Bundle

With adds new middleware(s) to the Group and returns a new Group with the updated middleware stack.

Jump to

Keyboard shortcuts

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