router

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: MIT Imports: 13 Imported by: 0

README

Router Module Documentation

Overview

The router module provides core types and logic for managing connection configurations and route groups in Go applications. It enables you to define connection types, group routes and middlewares, and manage them through a central Router struct. The module supports both HTTP and NATS connections, with NATS functionality provided via the NatsServer type.

Usage

Define Connection Configurations
configs := []router.Configs{
    {
        Port: 8080,
        Host: "localhost",
        ApiKey: "your-api-key",
        Type: router.HTTP,
    },
    {
        Port: 4222,
        Host: "nats-server",
        ApiKey: "nats-key",
        Type: router.NATS,
    },
}
Define Route Groups
routes := []router.Routes{
    {
        Base: "/api/v1",
        Routes: []router.Route{
            // Define Route structs here
        },
        Middlewares: []router.Middleware{
            // Define Middleware structs here
        },
    },
}
Create and Use the Router
r := router.NewRouter(configs, routes)
r.AddConfig(router.Configs{Port: 3000, Host: "127.0.0.1", Type: router.HTTP})
r.AddRoute(router.Routes{Base: "/api/v2"})
err := r.Run()
if err != nil {
    // handle error
}
Using NatsServer Directly
natsConfig := router.Configs{Port: 4222, Host: "localhost", Type: router.NATS}
routes := router.Routes{/* ... */}
natsServer := router.NatsServer{Configs: natsConfig}
err := natsServer.ConnectNats(routes)
if err != nil {
    // handle error
}

API Reference

Types
ConnectionType

Represents the type of connection. Possible values:

  • router.HTTP
  • router.NATS
Configs

Connection configuration.

  • Port int: Port number.
  • Host string: Host address.
  • ApiKey string: API key.
  • Type ConnectionType: Connection type.

Methods:

  • ConnectionTypeAllowed() bool: Checks if the type is supported.
  • Connect() error: Validates the connection type.
Routes

Group of routes and middlewares.

  • Routes []Route: List of routes.
  • Middlewares []Middleware: List of middlewares.
  • Base string: Base path.

Methods:

  • GetFullPath(path string) string: Returns base + path.
  • ToJSON() string: JSON representation.
Router

Central struct for managing configs and routes.

  • Configs []Configs: Connection configs.
  • Routes []Routes: Route groups.

Methods:

  • NewRouter(configs, routes) *Router: Creates a router.
  • GetConfigs() []Configs: Gets configs.
  • GetRoutes() []Routes: Gets routes.
  • AddConfig(config Configs): Adds a config.
  • AddRoute(route Routes): Adds a route group.
  • SetConfigs(configs []Configs): Sets configs.
  • SetRoutes(routes []Routes): Sets routes.
  • Run() error: Starts servers for each config and route group (delegates to other modules).
NatsServer

Handles NATS connections and subscriptions.

  • Configs Configs: NATS connection configuration.
  • nc *nats.Conn: NATS connection instance.

Methods:

  • ConnectNats(routes Routes) error: Connects to a NATS server and subscribes to routes. If connection fails, starts an embedded NATS server and retries.
  • handle(routes Routes) error: Subscribes to each route and handles incoming NATS messages.
  • startEmbeddedNATS() *server.Server: Starts an embedded NATS server if external connection fails.
  • contextFromMetadata(md nats.Msg) context.Context: Extracts metadata from a NATS message into a context.

Notes

  • The router module does not implement HTTP or NATS server logic directly in the Router type; NATS logic is handled by NatsServer.
  • Route and Middleware types must be defined elsewhere in your codebase.
  • Requires github.com/nats-io/nats.go and github.com/nats-io/nats-server/v2/server for NATS functionality.

License

This module is licensed under the MIT License.

Documentation

Index

Constants

View Source
const EndpointTypeHTTP = "http"
View Source
const EndpointTypeNATS = "nats"

Variables

This section is empty.

Functions

func InList added in v0.0.2

func InList[T comparable](value T, list []T) bool

Types

type Configs

type Configs struct {
	Port   int            `json:"port"`
	Host   string         `json:"host"`
	ApiKey string         `json:"api_key"`
	Type   ConnectionType `json:"type"`
}

func (Configs) Connect

func (c Configs) Connect() error

func (Configs) ConnectionTypeAllowed

func (c Configs) ConnectionTypeAllowed() bool

type ConnectionType

type ConnectionType string
const (
	HTTP ConnectionType = "http"
	NATS ConnectionType = "nats"
)

type Endpoint

type Endpoint interface {
	Parse(context.Context, *Request) (context.Context, error)
	Validate(context.Context) (context.Context, error)
	Handle(context.Context) (*Response, error)
	GetPath() string
	GetMethod() Method
	GetTypes() []string
}

type HttpServer

type HttpServer struct {
	Configs Configs `json:"configs" yaml:"configs"`
	// contains filtered or unexported fields
}

func (*HttpServer) Start

func (h *HttpServer) Start(routes Routes) error

type Method

type Method string
const (
	GetMethod     Method = "GET"
	PostMethod    Method = "POST"
	PutMethod     Method = "PUT"
	DeleteMethod  Method = "DELETE"
	PatchMethod   Method = "PATCH"
	HeadMethod    Method = "HEAD"
	OptionsMethod Method = "OPTIONS"
	TraceMethod   Method = "TRACE"
	ConnectMethod Method = "CONNECT"
)

type Middleware

type Middleware struct {
	Fn    func(ctx context.Context, r *Request) error
	Name  string
	ActOn []string
}

func NewMiddleware

func NewMiddleware(fn func(ctx context.Context, r *Request) error, name string) *Middleware

func (*Middleware) GetFn

func (m *Middleware) GetFn() func(ctx context.Context, r *Request) error

func (*Middleware) GetName

func (m *Middleware) GetName() string

func (*Middleware) Run

func (m *Middleware) Run(ctx context.Context, r *Request) error

func (*Middleware) SetFn

func (m *Middleware) SetFn(fn func(ctx context.Context, r *Request) error)

func (*Middleware) SetName

func (m *Middleware) SetName(name string)

func (*Middleware) ShouldActOn added in v0.0.3

func (m *Middleware) ShouldActOn(method string) bool

type NatsServer

type NatsServer struct {
	Configs Configs `json:"configs" yaml:"configs"`
	// contains filtered or unexported fields
}

func (*NatsServer) ConnectNats

func (s *NatsServer) ConnectNats(routes Routes) error

type Request

type Request struct {
	Body        map[string]interface{}             `json:"body"`
	Header      map[string]interface{}             `json:"header"`
	QueryParams map[string]interface{}             `json:"query_params,omitempty"`
	Params      map[string]interface{}             `json:"params,omitempty"`
	Files       map[string][]*multipart.FileHeader `json:"files,omitempty"`
	FormFields  map[string][]string                `json:"form_fields,omitempty"`
	Context     context.Context                    `json:"-"`
}

func (*Request) AssignTo

func (r *Request) AssignTo(dest interface{}) error

func (*Request) GetBody

func (r *Request) GetBody() map[string]interface{}

func (*Request) GetContext

func (r *Request) GetContext() context.Context

func (*Request) GetFiles

func (r *Request) GetFiles() map[string][]*multipart.FileHeader

func (*Request) GetFormFields

func (r *Request) GetFormFields() map[string][]string

func (*Request) GetHeader

func (r *Request) GetHeader() map[string]interface{}

func (*Request) GetParams

func (r *Request) GetParams() map[string]interface{}

func (*Request) GetQueryParams

func (r *Request) GetQueryParams() map[string]interface{}

func (*Request) GetValue

func (r *Request) GetValue(key string) interface{}

func (*Request) HasBody

func (r *Request) HasBody(key string) bool

func (*Request) HasFile

func (r *Request) HasFile(key string) bool

func (*Request) HasFormField

func (r *Request) HasFormField(key string) bool

func (*Request) HasHeader

func (r *Request) HasHeader(key string) bool

func (*Request) HasParam

func (r *Request) HasParam(key string) bool

func (*Request) HasQueryParam

func (r *Request) HasQueryParam(key string) bool

func (*Request) HasValue

func (r *Request) HasValue(key string) bool

func (*Request) SetBodyValue

func (r *Request) SetBodyValue(key string, value interface{})

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context)

func (*Request) SetFileValue

func (r *Request) SetFileValue(key string, value []*multipart.FileHeader)

func (*Request) SetFormFieldValue

func (r *Request) SetFormFieldValue(key string, value []string)

func (*Request) SetHeaderValue

func (r *Request) SetHeaderValue(key string, value interface{})

func (*Request) SetParamValue

func (r *Request) SetParamValue(key string, value interface{})

func (*Request) SetQueryParamValue

func (r *Request) SetQueryParamValue(key string, value interface{})

func (*Request) ToJsonBytes

func (r *Request) ToJsonBytes() ([]byte, error)

type Response

type Response struct {
	Data   any      `json:"results,omitempty"`
	Errors []string `json:"errors,omitempty"`
	Code   int      `json:"code"`
}

func NewErrorResponse

func NewErrorResponse(errors []string, code int) *Response

func NewResponse

func NewResponse(data any, code int) *Response

func (*Response) GetCode

func (r *Response) GetCode() int

func (*Response) GetData

func (r *Response) GetData() any

func (*Response) GetErrors

func (r *Response) GetErrors() []string

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

func (*Response) SetCode

func (r *Response) SetCode(code int)

func (*Response) SetData

func (r *Response) SetData(data any)

func (*Response) SetErrors

func (r *Response) SetErrors(errors []string)

func (*Response) ToJsonBytes

func (r *Response) ToJsonBytes() []byte

type Route

type Route struct {
	Endpoint         Endpoint
	TimeoutInSeconds int
}

func (*Route) Handle

func (r *Route) Handle(ctx context.Context, request *Request) (*Response, error)

type Router

type Router struct {
	Configs []Configs `json:"configs"`
	Routes  []Routes  `json:"routes"`
}

func NewRouter

func NewRouter(configs []Configs, routes []Routes) *Router

func (*Router) AddConfig

func (r *Router) AddConfig(config Configs)

func (*Router) AddRoute

func (r *Router) AddRoute(route Routes)

func (*Router) GetConfigs

func (r *Router) GetConfigs() []Configs

func (*Router) GetRoutes

func (r *Router) GetRoutes() []Routes

func (*Router) Run

func (r *Router) Run() error

func (*Router) SetConfigs

func (r *Router) SetConfigs(configs []Configs)

func (*Router) SetRoutes

func (r *Router) SetRoutes(routes []Routes)

type Routes

type Routes struct {
	Routes      []Route      `json:"routes"`
	Middlewares []Middleware `json:"middlewares"`
	Base        string       `json:"base"`
}

func (Routes) GetFullPath

func (r Routes) GetFullPath(path string) string

func (Routes) ToJSON

func (r Routes) ToJSON() string

Jump to

Keyboard shortcuts

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