wayes

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2024 License: MIT Imports: 6 Imported by: 0

README

wayes : 🌐 simple router using http.ServeMux

Package wayes provides a convenient wrapper around the standard router of the net/http package. Describing routes is as simple as in favorite frameworks like Fiber, Gin, and others.

wayes only works with Go 1.22+ as it requires the new net/http package.

Installation

go get github.com/eliofery/wayes

Usage

Example of creating and grouping routes.

// Create a new router with use go-playground/validator.
// Validator should implement the interface wayes.Validater.
router := wayes.New(validator.New())

// Also, you can use the router without employing a validator.
// router := wayes.New()

// Create a route group for endpoints.
users := router.Group("/users")
{
    // Define a GET handler for the "/users/welcome" endpoint.
    // Also, there are other HTTP methods available, such as POST, PUT, PATCH, DELETE, OPTIONS, and HEAD.
    users.Get("/welcome", func(ctx wayes.Ctx) error {
        return ctx.JSON(wayes.Response{
            Success: true,
            Message: "Hi bro",
            Data: wayes.Map{
                "foo": "bar",
                "baz": 123,
            },
        })
    })

    // Define a POST handler for the "/users/welcome" endpoint.
    // Decodes the request body into the provided data and validates it.
    users.Post("/welcome", func(ctx wayes.Ctx) error {
        type User struct {
            Name string `json:"name" validate:"required"`
        }

        var user User
        if err := ctx.Validate(&user); err != nil {
            return ctx.Status(http.StatusBadRequest).SendError(err)
        }

        return ctx.JSON(wayes.Response{
            Success: true,
            Data:    user,
        })
    })
}

// Start the server.
if err := http.ListenAndServe(":8081", router.Mux()); err != nil {
    log.Fatal(err)
}
Middlewares

Example of creating middlewares.

// Cors is a middleware that sets CORS headers.
func Cors() wayes.Handler {
    return func(ctx wayes.Ctx) error {
        ctx.Set("Access-Control-Allow-Origin", "*")
        ctx.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
        ctx.Set("Access-Control-Allow-Headers", "Origin, Accept, Authorization, Content-Type, X-CSRF-Token")
        ctx.Set("Access-Control-Expose-Headers", "Link, Content-Length, Access-Control-Allow-Origin")
        ctx.Set("Access-Control-Max-Age", "0")
        
        return ctx.Next()
    }
}

func main() {
    // Create a new router with use go-playground/validator.
    // Validator should implement the interface wayes.Validater.
    router := wayes.New(validator.New())
    
    fooMiddleware := func(ctx wayes.Ctx) error {
        return ctx.Next()
    }
    
    barMiddleware := func(ctx wayes.Ctx) error {
        if rand.IntN(2) == 1 {
            err := errors.New("access denied")
            return ctx.Status(http.StatusForbidden).SendError(err)
        }
        
        return ctx.Next()
    }
    
    // Define middleware for the all routes.
    router.Use(Cors(), fooMiddleware)
    
    // Create a route group for endpoints.
    users := router.Group("/users")
    {
        // Define middleware for the user group.
        users.Use(barMiddleware)
        
        // Define a GET handler for the "/users/welcome" endpoint.
        users.Get("/welcome", func(ctx wayes.Ctx) error {
            return ctx.JSON(wayes.Response{
                Success: true,
                Message: "Hi bro",
                Data: wayes.Map{
                    "foo": "bar",
                    "baz": 123,
                },
            })
        })
    }
    
    // Start the server.
    if err := http.ListenAndServe(":8081", router.Mux()); err != nil {
        log.Fatal(err)
    }
}

Combine routers

Example of creating merged routes.

// Create a new routers.
router := wayes.New(validator.New())
router2 := wayes.New()

// Create a route group for endpoints.
groupV1 := router.Group("/v1")
groupV2 := router2.Group("/v2")

// Define a GET handler for the "/v1/users" endpoint.
groupV1.Get("/users", func(ctx wayes.Ctx) error {
    return ctx.JSON(wayes.Response{
        Success: true,
        Message: "response users version 1",
    })
})

// Define a GET handler for the "/v2/users" endpoint.
groupV2.Get("/users", func(ctx wayes.Ctx) error {
    return ctx.JSON(wayes.Response{
        Success: true,
        Message: "response users version 2",
    })
})

// Combine routers into a single router.
// Now routes created in another router are accessible within a single router.
router.Combine(router2.Mux())

// Start the server.
if err := http.ListenAndServe(":8081", router.Mux()); err != nil {
    log.Fatal(err)
}

Inspiration

I was inspired to write this package by the http, fiber and gin.

Documentation

Overview

Package wayes provides a convenient wrapper around the standard router of the pkg/net/http.ServeMux package. Describing routes is as simple as in favorite frameworks like Fiber, Gin, and others.

Includes Wayes that serves as a wrapper for the standard pkg/net/http.ServeMux package.

Includes Ctx that allows passing context. Context to middleware and handlers for request-specific data.

Demonstrates how to define routes and handlers using the wayes package. It initializes a new wayes and creates a route group for user-related endpoints. Within the user group, it defines various HTTP methods (GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD) that can be used to interact with user data.

// Create a new router with use go-playground/validator.
// Validator should implement the interface wayes.Validater.
router := wayes.New(validator.New())

// Also, you can use the router without employing a validator.
// router := wayes.New()

// Create a route group for endpoints.
users := router.Group("/users")
{
	// Define a GET handler for the "/users/welcome" endpoint.
	// Also, there are other HTTP methods available, such as POST, PUT, PATCH, DELETE, OPTIONS, and HEAD.
	users.Get("/welcome", func(ctx wayes.Ctx) error {
		return ctx.JSON(wayes.Response{
			Success: true,
			Message: "Hi bro",
			Data: wayes.Map{
				"foo": "bar",
				"baz": 123,
			},
		})
	})

	// Define a POST handler for the "/users/welcome" endpoint.
	// Decodes the request body into the provided data and validates it.
	users.Post("/welcome", func(ctx wayes.Ctx) error {
		type User struct {
			Name string `json:"name" validate:"required"`
		}

		var user User
		if err := ctx.Validate(&user); err != nil {
			return ctx.Status(http.StatusBadRequest).SendError(err)
		}

		return ctx.JSON(wayes.Response{
			Success: true,
			Data:    user,
		})
	})
}

// Start the server.
if err := http.ListenAndServe(":8081", router.Mux()); err != nil {
	log.Fatal(err)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Ctx

type Ctx interface {
	// Response returns the underlying [http.ResponseWriter] associated with the context.
	Response() http.ResponseWriter

	// Request returns the underlying [http.Request] associated with the context.
	Request() *http.Request

	// Locals sets or retrieves values associated with the context using the provided key.
	Locals(key any, value ...any) any

	// Status sets the status code for the response.
	Status(status int) Ctx

	// Get returns the header value for the given key.
	Get(key string, defaultValue ...string) string

	// Set sets the header value for the given key.
	Set(key, value string)

	// ContentType sets the Content-Type header for the response.
	ContentType(value string)

	// Decode decodes the request body into the provided data.
	Decode(data any) error

	// Validate decodes and validates the request body into the provided data.
	Validate(data any) error

	// Encode encodes the provided data into the response body.
	Encode(data any) error

	// Write sends a plain text response message to the user.
	Write(message string) error

	// JSON sends a json object response message to the user.
	JSON(data any) error

	// Next executes the next handler in the chain.
	Next() error

	// SendStatus sends an HTTP status code to the user.
	SendStatus(code int) error

	// SendError creates and returns an error with the specified message.
	SendError(message error) error
}

Ctx represents a structure for a context.

func NewCtx

func NewCtx(validator Validater, w http.ResponseWriter, r *http.Request) Ctx

NewCtx creates a new instance of Ctx.

type Handler

type Handler func(ctx Ctx) error

Handler defines a function signature for handling HTTP requests.

type Map

type Map map[string]any

Map represents a map of key-value pairs.

type Response

type Response struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
	Data    any    `json:"data,omitempty"`
}

Response represents a structure for a response.

type Validater

type Validater interface {
	// Struct validates the structure of the provided data against predefined rules and
	// returns any validation errors encountered.
	Struct(data any) error
}

Validater is an interface that defines methods for configuring and performing validation.

type Wayes

type Wayes interface {
	// Head registers a handler function for the HEAD method and the specified path.
	Head(path string, handler Handler)

	// Get registers a handler function for the GET method and the specified path.
	Get(path string, handler Handler)

	// Options registers a handler function for the Options method and the specified path.
	Options(path string, handler Handler)

	// Post registers a handler function for the POST method and the specified path.
	Post(path string, handler Handler)

	// Patch registers a handler function for the PATCH method and the specified path.
	Patch(path string, handler Handler)

	// Put registers a handler function for the PUT method and the specified path.
	Put(path string, handler Handler)

	// Delete registers a handler function for the DELETE method and the specified path.
	Delete(path string, handler Handler)

	// Group creates a new route group.
	Group(path string) Wayes

	// Use registers middleware for the wayes.
	Use(handlers ...Handler)

	// Combine combines multiple routers into a single wayes.
	Combine(routers ...*http.ServeMux) *http.ServeMux

	// Mux returns the underlying http.ServeMux.
	Mux() *http.ServeMux
}

Wayes is an interface that defines methods for working with HTTP routes.

func New

func New(validator ...Validater) Wayes

New creates a new instance of Wayes.

Jump to

Keyboard shortcuts

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