gouter

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2025 License: MIT Imports: 10 Imported by: 0

README

🚀 Gouter - Lightweight HTTP Router for Go

Go Report Card

Gouter is a minimalist yet powerful HTTP router for Go, designed for building high-performance web applications and APIs. Inspired by Express.js and standard lib from golang, it combines simplicity with essential features for modern web development.

✨ Features

  • 🛣️ Intuitive Routing with dynamic parameters
  • 🔌 Middleware Support for modular code
  • 🧩 Route Grouping with shared prefixes and middleware
  • 📡 HTTPS/HTTP2 Support out of the box
  • 📊 Automatic Body Parsing with intelligent buffering
  • 📝 Structured Logging with color-coded output
  • 🚦 Error Handling with JSON error responses
  • High Performance with concurrent connection handling

📦 Installation

go get github.com/Murilinho145SG/gouter

🚀 Quick Start

package main

import (
	"github.com/Murilinho145SG/gouter"
	"github.com/Murilinho145SG/gouter/httpio"
)

func main() {
	r := gouter.NewRouter()
	
	r.Route("/", func(w httpio.Writer, req *httpio.Request) {
		w.WriteJson(map[string]string{"message": "Welcome to Gouter!"}, false)
	})

	r.Route("/user/:name", func(w httpio.Writer, req *httpio.Request) {
		name, _ := req.Params.Get("name")
		w.WriteJson(map[string]string{"hello": name}, false)
	})

	gouter.Run(":8080", r)
}

🛠️ Advanced Usage

Middleware Example

func Logger(next gouter.Handler) gouter.Handler {
	return func(w httpio.Writer, r *httpio.Request) {
		log.Info("Request:", r.Method, r.Path)
		next(w, r)
	}
}

func main() {
	r := gouter.NewRouter()
	r.Use(Logger)
	
	// Routes...
}

Route Groups

func main() {
	r := gouter.NewRouter()
	
	api := r.Group("/api")
	api.Use(JWTAuth)
	
	api.Route("/users", UsersHandler)
	api.Route("/posts", PostsHandler)
}

Dynamic Routes

r.Route("/product/:category/:id", func(w httpio.Writer, r *httpio.Request) {
	category, _ := r.Params.Get("category")
	id, _ := r.Params.Get("id")
	// Handle request...
})

Error Handling

r.OnError = func(w httpio.Writer, code uint, err error) {
	w.WriteHeader(code)
	w.WriteJson(map[string]string{
		"error": err.Error(),
		"code":  strconv.Itoa(int(code)),
	}, false)
}

HTTPS Support

err := gouter.RunTLS(
	":443",
	r,
	"cert.pem",
	"key.pem",
)

📊 Logging Enable debug mode for detailed request logging:

r.SetDebugMode()

🤝 Contributing We welcome contributions! Please see our Contribution Guidelines for details.

📄 License MIT License - See LICENSE for details.

Happy Routing! 🎉 Built with ❤️ by Murilinho145

Documentation

Index

Constants

View Source
const (
	// DefaultBuffer is the default buffer size used for reading connections,
	// if no custom configuration is provided.
	DefaultBuffer = 8192

	// MaxHeaderSize defines the maximum allowed size for HTTP headers.
	// In this example, it is limited to 10 KB.
	MaxHeaderSize = 10 * 1024

	// MaxBodySize defines the maximum allowed size for the HTTP request body.
	// In this example, it is limited to 1 MB.
	MaxBodySize = 1 * 1024 * 1024
)

Variables

View Source
var (
	ErrSearchNotFound = errors.New("this path is not registered")
)

Predefined error for when a route is not found.

Functions

func Run

func Run(addrs string, router *Router, server ...Server) error

Run starts an HTTP server on the specified address and handles incoming connections using the provided router.

Parameters:

  • addrs: The address (host:port) on which the server should listen.
  • router: The router instance that manages routes and their handlers.
  • server: (Optional) Custom server configurations.

Returns:

  • An error if creating the listener or processing connections fails.

func RunTLS

func RunTLS(addrs string, router *Router, certStr, key string, server ...Server) error

RunTLS starts an HTTPS server on the specified address using the provided TLS certificate and key.

Parameters:

  • addrs: The address (host:port) where the HTTPS server should listen.
  • router: The router instance for managing routes.
  • certStr: The path to the TLS certificate.
  • key: The path to the private key corresponding to the certificate.
  • server: (Optional) Custom server configurations.

Returns:

  • An error if TLS configuration, listener creation, or connection processing fails.

Types

type Group

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

Group represents a group of routes with a common prefix and shared middleware.

func NewGroup

func NewGroup(router *Router, pathGroup string) *Group

NewGroup creates and returns a new Group instance.

func (*Group) Route

func (g *Group) Route(route string, handler Handler)

Route registers a route within the group. Middleware specific to the group is applied to the handler.

func (*Group) UseGroup

func (g *Group) UseGroup(mw Middleware)

UseGroup adds middleware to the group.

type GroupFunc

type GroupFunc func(g *Group)

GroupFunc is a function type used to define route groups.

type Handler

type Handler func(w httpio.Writer, r *httpio.Request)

Handler is a function type that handles HTTP requests. It takes a Writer to send responses and a Request containing the request data.

type HandlersList

type HandlersList map[string]Handler

HandlersList is a map that associates route paths with their corresponding handlers.

func (HandlersList) GetHandler

func (h HandlersList) GetHandler(path string) Handler

GetHandler retrieves the handler associated with a given path.

func (HandlersList) NewRoute

func (h HandlersList) NewRoute(path string, handler Handler)

NewRoute registers a new route with its handler. If the route already exists, a warning is logged.

func (HandlersList) Search

func (h HandlersList) Search(path string) error

Search checks if a route exists in the HandlersList. Returns ErrSearchNotFound if the route is not found.

type Middleware

type Middleware func(Handler) Handler

Middleware is a function type that wraps a Handler to provide additional functionality.

type Router

type Router struct {
	Routes HandlersList // Map of routes and their handlers
	// contains filtered or unexported fields
}

Router is the main router structure that manages routes and middleware.

func NewRouter

func NewRouter() *Router

NewRouter creates and returns a new instance of Router with an empty route map.

func (*Router) Group

func (r *Router) Group(pathGroup string, handler GroupFunc)

Group creates a new route group with a common prefix and optional middleware.

func (*Router) OnError

func (r *Router) OnError(w httpio.Writer, code uint, err error)

OnError sends an error response with the specified status code and error message.

func (*Router) ParseRoute

func (r *Router) ParseRoute(req *httpio.Request) Handler

ParseRoute matches the request path to a registered route and returns the corresponding handler. It supports dynamic route parameters (e.g., `/user/:id`).

func (*Router) Route

func (r *Router) Route(route string, handler Handler)

Route registers a new route with the router. Middleware is applied to the handler before registration.

func (*Router) SetDebugMode

func (r *Router) SetDebugMode()

SetDebugMode enables debug logging for the router.

func (*Router) Use

func (r *Router) Use(mw Middleware)

Use adds middleware to the router.

type Server

type Server struct {
	// InitialReadSize specifies the initial buffer size used for reading from the connection.
	// If set to zero, DefaultBuffer will be used.
	InitialReadSize int

	// InitialReadChunk indicates whether the connection should be read in chunks (true)
	// or in a single block (false).
	InitialReadChunk bool
}

Server defines configuration options for the HTTP server.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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