invoke

package module
v0.0.0-...-f1d2d96 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2024 License: MIT Imports: 29 Imported by: 0

README

Invoke

Invoke is a lightweight trie-based HTTP router for Go. It supports static routes, parameterized routes, regex routes, and middleware hooks for before and after route handling. This router is designed to be simple and efficient, making it ideal for small to medium-sized web applications.

Note: This project was 100% generated by ChatGPT-4.

Features

  • Static Routes: Define static routes with fixed paths.
  • Parameterized Routes: Define dynamic routes with parameters, e.g., /user/:id.
  • Regex Routes: Define routes with regex patterns, e.g., /product/{id:[0-9]+}.
  • Middleware Hooks: Support for global and group-specific before and after hooks.
  • 404 Not Found Handler: Customizable handler for 404 errors.
  • Static File Serving: Built-in support for serving static files.
  • Custom Recovery handler:An optional custom handler for panics, allowing for specific error handling logic.

Installation

go get github.com/bytepai/invoke

Usage

Basic Example
package main

import (
	"fmt"
	. "github.com/bytepai/invoke"
)

func main() {
	r := NewRouter()

	// Set custom 404 handler
	r.SetNotFoundHandler(func(ctx *HttpContext) {
		ctx.WriteString("Custom 404 - Not Found")
	})

	r.GET("/", func(ctx *HttpContext) {
		ctx.WriteString("index")
	})

	r.GET("/hello", func(ctx *HttpContext) {
		ctx.WriteString("Hello, world!")
	})

	r.GET("/user/:name", func(ctx *HttpContext) {
		name := ctx.Params["name"]
		ctx.WriteString(fmt.Sprintf("Hello, %s!", name))
	})

	r.GET("/order/:id", func(ctx *HttpContext) {
		id := ctx.Params["id"]
		ctx.WriteString(fmt.Sprintf("Order ID: %s", id))
	})
	r.POST("/product/{id:[0-9]+}", func(ctx *HttpContext) {
		id := ctx.Params["id"]
		ctx.WriteSuccessJSON(id)
	})
	r.GET("/phone/{phone:1[3456789]\\d{9}}", func(ctx *HttpContext) {
		phone := ctx.Params["phone"]
		ctx.WriteString(fmt.Sprintf("Hello, %s!", phone))
	})
	fmt.Println("Server listening on port 8080...")
	r.ListenAndServe(":8080")
}
Grouping Routes
package main

import (
	"fmt"
	. "github.com/bytepai/invoke"
)

func main() {
	r := NewRouter()

	// Create a new group
	apiGroup := r.Group("/api")

	// Register group before hook
	apiGroup.RegisterGroupBeforeHook(func(ctx *HttpContext) bool {
		fmt.Println("API group before hook")
		return true // Return false to terminate
	})

	// Register group after hook
	apiGroup.RegisterGroupAfterHook(func(ctx *HttpContext) {
		fmt.Println("API group after hook")
	})

	// Add routes to the group
	apiGroup.GET("/info", func(ctx *HttpContext) {
		ctx.WriteString("API Info")
	})

	fmt.Println("Server listening on port 8080...")
	r.ListenAndServe(":8080")
}
Middleware Hooks
package main

import (
	"fmt"
	. "github.com/bytepai/invoke"
)

func main() {
	r := NewRouter()

	// Register global before hook
	r.RegisterBeforeHook(func(ctx *HttpContext) bool {
		fmt.Println("Global before hook")
		return true
	})

	// Register global after hook
	r.RegisterAfterHook(func(ctx *HttpContext) {
		fmt.Println("Global after hook")
	})

	r.SetRecoveryHandler(func(ctx *HttpContext, err interface{}) {
		errString := fmt.Sprintf("Custom recovery handler: %v\n", err)
		ctx.WriteString(errString)
	})
	
	r.POST("/panic", func(ctx *HttpContext) {
		var s []string
		fmt.Println(s[1])
	})

	fmt.Println("Server listening on port 8080...")
	r.ListenAndServe(":8080")
}
Serve
Router->Serve(config)
	Router.StartServer(":8080") 
	Router.StartServer("localhost:8080")
	Router.StartServerConfig(ServerConfig)
	
Serve(config,router)
    Server.Start("localhost:8080",Router)
	Server.StartConfig(ServerConfig,Router)

Documentation

Index

Constants

View Source
const MaxMultipartBytes = 32 << 20 // 32 MB
View Source
const ParamsKey = contextKey("params")

ParamsKey is the context key for route parameters.

Variables

View Source
var ErrorCodeToString = map[ErrorCode]string{
	AuthError:  "AuthError",
	ParamError: "ParamError",
	BizError:   "BizError",
	NetError:   "NetError",
	DBError:    "DBError",
	IOError:    "IOError",
	OtherError: "OtherError",
}

ErrorCodeToString maps ErrorCode values to their corresponding strings.

View Source
var Router = NewRouter()
View Source
var String stringHandler

String is a package-level variable representing a string handler.

View Source
var Time timeHandler

Time is a package-level variable representing a time handler.

Functions

func Bool2Str

func Bool2Str(b bool) string

Bool2Str converts a boolean to a string.

func Float2Int

func Float2Int(num float64) int

Float2Int converts a float64 to an integer.

func Float2Str

func Float2Str(num float64) string

Float2Str converts a float64 to a string.

func GetParams

func GetParams(req *http.Request) map[string]string

GetParams retrieves the route parameters from the request context.

func Int2Float

func Int2Float(num int) float64

Int2Float converts an integer to a float64.

func Int2Str

func Int2Str(num int) string

Int2Str converts an integer to a string.

func MimeText

func MimeText(ext string) string

func NewRouter

func NewRouter() *router

NewRouter creates a new router with an empty root node.

func RegisterMiddleware

func RegisterMiddleware(name string, middleware func(http.Handler) http.Handler)

Middleware registration function

func RegisterServer

func RegisterServer(config ServerConfig)

Server registration function with configuration synchronization

func Rune2Str

func Rune2Str(r rune) string

Rune2Str This function converts a Unicode code point into its corresponding string representation, handling printable ASCII characters, control characters, and Unicode escape sequences.

func StartServer

func StartServer(r ...*router)

func Str2Bool

func Str2Bool(str string) (bool, error)

Str2Bool converts a string to a boolean.

func Str2Float

func Str2Float(str string) (float64, error)

Str2Float converts a string to a float64.

func Str2Int

func Str2Int(str string) (int, error)

Str2Int converts a string to an integer.

func Str2Int64

func Str2Int64(str string) (int64, error)

Str2Int64 converts a string to an int64.

func ToBool

func ToBool(src interface{}) (interface{}, error)

ToBool converts an interface{} to a boolean. Bool is a ValueConverter that converts input values to bools.

The conversion rules are:

  • booleans are returned unchanged
  • for integer types, 1 is true 0 is false, other integers are an error
  • for strings and []byte, same rules as strconv.ParseBool
  • all other types are an error

func ToFloat

func ToFloat(value interface{}) (float64, error)

ToFloat converts an interface{} to a float64.

func ToInt

func ToInt(value interface{}) (int, error)

ToInt converts an interface{} to an integer.

func ToInt64

func ToInt64(v interface{}) (interface{}, error)

ToInt64 converts an interface{} to a int64

func ToString

func ToString(value interface{}) string

ToString converts an interface{} to a string.

Types

type CORSConfig

type CORSConfig struct {
	AllowedOrigins []string `json:"allowed_origins"`
	AllowedMethods []string `json:"allowed_methods"`
	AllowedHeaders []string `json:"allowed_headers"`
}

type CompressionConfig

type CompressionConfig struct {
	EnableGzip       bool `json:"enable_gzip"`
	CompressionLevel int  `json:"compression_level"`
}

type Config

type Config struct {
	Servers []ServerConfig `json:"servers"`
}

type DatabaseConfig

type DatabaseConfig struct {
	PostgreSQL PostgreSQLConfig `json:"postgresql"`
	Oracle     OracleConfig     `json:"oracle"`
	SQLite     SQLiteConfig     `json:"sqlite"`
	MySQL      MySQLConfig      `json:"mysql"`
	MongoDB    MongoDBConfig    `json:"mongodb"`
	Redis      RedisConfig      `json:"redis"`
}
var (
	DBConfig *DatabaseConfig
)

func InitializeDBConfig

func InitializeDBConfig() (*DatabaseConfig, error)

func LoadDBConfig

func LoadDBConfig(filePath string) (*DatabaseConfig, error)

LoadDBConfig loads configuration from a JSON file

type ErrorCode

type ErrorCode int

ErrorCode represents custom error codes.

const (
	// AuthError indicates an error related to permission.
	AuthError ErrorCode = iota*1000 + 1000
	// ParamError indicates an error related to parameters.
	ParamError
	// BizError indicates a business logic error.
	BizError
	// NetError indicates a network-related error.
	NetError
	// DBError indicates a database-related error.
	DBError
	// IOError indicates an I/O-related error.
	IOError
	// OtherError indicates an error that does not fall into any specific category.
	OtherError
)

func (ErrorCode) String

func (ec ErrorCode) String() string

ErrorCodeToString converts an ErrorCode value to its corresponding string.

type FileHandler

type FileHandler func(key string, file multipart.File, fileHeader *multipart.FileHeader)

FileHandler is a callback function type for handling file data.

type FormDataHandler

type FormDataHandler func(key string, value string)

FormDataHandler is a callback function type for handling form data key-value pairs.

type HttpContext

type HttpContext struct {
	W      http.ResponseWriter
	Req    *http.Request
	Params map[string]string
}

HttpContext represents the HTTP context.

func (*HttpContext) AddCookie

func (ctx *HttpContext) AddCookie(cookie *http.Cookie)

AddCookie adds a Set-Cookie header to the provided ResponseWriter's headers.

func (*HttpContext) Body

func (ctx *HttpContext) Body() io.ReadCloser

Body returns the request body.

func (*HttpContext) CloseNotify

func (ctx *HttpContext) CloseNotify() <-chan bool

CloseNotify returns a channel that receives a single value when the client connection has gone away.

func (*HttpContext) ContentLength

func (ctx *HttpContext) ContentLength() int64

ContentLength returns the length of the request body.

func (*HttpContext) Flush

func (ctx *HttpContext) Flush()

Flush sends any buffered data to the client.

func (*HttpContext) FormValue

func (ctx *HttpContext) FormValue(key string) string

FormValue returns the first value for the named component of the query.

func (*HttpContext) Header

func (ctx *HttpContext) Header() http.Header

Header returns the header map that will be sent by WriteHeader.

func (*HttpContext) Hijack

func (ctx *HttpContext) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack hijacks the connection.

func (*HttpContext) Host

func (ctx *HttpContext) Host() string

Host returns the host name provided by the request.

func (*HttpContext) Method

func (ctx *HttpContext) Method() string

Method returns the HTTP request method.

func (*HttpContext) ParmBool

func (ctx *HttpContext) ParmBool(key string) (bool, error)

ParmBool parses a boolean parameter from the request.

func (*HttpContext) ParmDataTime

func (ctx *HttpContext) ParmDataTime(key string) (time.Time, error)

ParmDataTime parses a date-time parameter (yyyy-mm-dd hh:mm:ss) from the request.

func (*HttpContext) ParmDate

func (ctx *HttpContext) ParmDate(key string) (time.Time, error)

ParmDate parses a date parameter (yyyy-mm-dd) from the request.

func (*HttpContext) ParmFloat

func (ctx *HttpContext) ParmFloat(key string) (float64, error)

ParmFloat parses a float parameter from the request.

func (*HttpContext) ParmInt

func (ctx *HttpContext) ParmInt(key string) (int64, error)

ParmInt parses an integer parameter from the request.

func (*HttpContext) ParmInt_

func (ctx *HttpContext) ParmInt_(key string) int64

ParmInt_ is an alternate method to parse an integer parameter from the request.

func (*HttpContext) ParmMonth

func (ctx *HttpContext) ParmMonth(key string) (time.Time, error)

ParmMonth parses a month parameter (yyyy-mm) from the request.

func (*HttpContext) ParmStr

func (ctx *HttpContext) ParmStr(key string) string

ParmStr parses a string parameter from the request.

func (*HttpContext) ParmStrings

func (ctx *HttpContext) ParmStrings(key string) []string

ParmStrings retrieves multiple values for a parameter from the request.

func (*HttpContext) ParmTime

func (ctx *HttpContext) ParmTime(key string) (time.Time, error)

ParmTime parses a time parameter (HH:MM) from the request.

func (*HttpContext) ParmTimeParse

func (ctx *HttpContext) ParmTimeParse(key string, format string) (time.Time, error)

ParmTimeParse parses a custom time format from the request.

func (*HttpContext) ParmYear

func (ctx *HttpContext) ParmYear(key string) (time.Time, error)

ParmYear parses a year parameter (yyyy) from the request.

func (*HttpContext) ParseJSONBody

func (ctx *HttpContext) ParseJSONBody(target interface{}) error

ParseJSONBody reads the JSON body from the request and unmarshals it into the target object.

func (*HttpContext) PostFormValue

func (ctx *HttpContext) PostFormValue(key string) string

PostFormValue returns the first value for the named component of the POST or PUT request body.

func (*HttpContext) Pusher

func (ctx *HttpContext) Pusher() http.Pusher

Pusher returns the HTTP/2 Pusher for the provided ResponseWriter.

func (*HttpContext) RemoteAddr

func (ctx *HttpContext) RemoteAddr() string

RemoteAddr returns the network address of the client sending the request.

func (*HttpContext) ReqHeader

func (ctx *HttpContext) ReqHeader() http.Header

ReqHeader returns the request header.

func (*HttpContext) SetCookie

func (ctx *HttpContext) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.

func (*HttpContext) URL

func (ctx *HttpContext) URL() *url.URL

URL returns the URL of the request.

func (*HttpContext) UserAgent

func (ctx *HttpContext) UserAgent() string

UserAgent returns the user agent string provided in the request header.

func (*HttpContext) Write

func (ctx *HttpContext) Write(data []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

func (*HttpContext) WriteByte

func (ctx *HttpContext) WriteByte(data []byte)

WriteByte writes byte to the client.

func (*HttpContext) WriteErrorJSON

func (ctx *HttpContext) WriteErrorJSON(statusCode interface{}, errMsg interface{})

WriteErrorJSON writes an error message as JSON to the response with the specified status code.

func (*HttpContext) WriteErrorXML

func (ctx *HttpContext) WriteErrorXML(statusCode int, errMsg interface{})

WriteErrorXML writes an error message as XML to the response with the specified status code.

func (*HttpContext) WriteHeader

func (ctx *HttpContext) WriteHeader(statusCode int)

WriteHeader sends an HTTP response header with the provided status code.

func (*HttpContext) WriteString

func (ctx *HttpContext) WriteString(s string)

WriteString writes a string to the response.

func (*HttpContext) WriteSuccessJSON

func (ctx *HttpContext) WriteSuccessJSON(data interface{})

WriteSuccessJSON writes an object as JSON to the response with a 200 status code.

func (*HttpContext) WriteSuccessXML

func (ctx *HttpContext) WriteSuccessXML(data interface{})

WriteSuccessXML writes an object as XML to the response with a 200 status code.

type KeepAliveConfig

type KeepAliveConfig struct {
	Enabled bool          `json:"enabled"`
	Timeout time.Duration `json:"timeout"`
}

type LoggingConfig

type LoggingConfig struct {
	AccessLog string `json:"access_log"`
	ErrorLog  string `json:"error_log"`
	LogLevel  string `json:"log_level"`
}

type MongoDBConfig

type MongoDBConfig struct {
	URI      string `json:"uri"`
	Database string `json:"database"`
}

type MySQLConfig

type MySQLConfig struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	DBName   string `json:"dbname"`
}

type NodeType

type NodeType int

NodeType represents the type of trie node.

const (
	Static NodeType = iota // Static node type for regular string nodes.
	Param                  // Param node type for parameter nodes, e.g., /user/:id.
	Regex                  // Regex node type for regex pattern nodes, e.g., /product/{regexp}.
)

type OracleConfig

type OracleConfig struct {
	User     string `json:"user"`
	Password string `json:"password"`
	DBName   string `json:"dbname"`
}

type PostgreSQLConfig

type PostgreSQLConfig struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	DBName   string `json:"dbname"`
	SSLMode  string `json:"sslmode"`
}

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int `json:"requests_per_second"`
}

type RedisConfig

type RedisConfig struct {
	Addr     string `json:"addr"`
	Password string `json:"password"`
	DB       int    `json:"db"`
}

type ResponseResult

type ResponseResult struct {
	Code int         `json:"code"`
	URL  string      `json:"url,omitempty"`
	Desc string      `json:"desc,omitempty"`
	Data interface{} `json:"data"`
}

ResponseResult represents a unified response structure.

type SQLiteConfig

type SQLiteConfig struct {
	DBPath string `json:"dbpath"`
}

type SecurityConfig

type SecurityConfig struct {
	AllowedHosts   []string   `json:"allowed_hosts"`
	CORS           CORSConfig `json:"cors"`
	CSRFProtection bool       `json:"csrf_protection"`
}

type ServerConfig

type ServerConfig struct {
	Domain         string            `json:"domain"`
	Port           int               `json:"port"`
	ReadTimeout    time.Duration     `json:"read_timeout"`
	WriteTimeout   time.Duration     `json:"write_timeout"`
	MaxHeaderBytes int               `json:"max_header_bytes"`
	TLS            TLSConfig         `json:"tls"`
	Limits         RateLimitConfig   `json:"limits"`
	RateLimit      RateLimitConfig   `json:"rate_limit"`
	Logging        LoggingConfig     `json:"logging"`
	Security       SecurityConfig    `json:"security"`
	Timeouts       TimeoutsConfig    `json:"timeouts"`
	KeepAlive      KeepAliveConfig   `json:"keep_alive"`
	Compression    CompressionConfig `json:"compression"`
	StaticFiles    StaticFilesConfig `json:"static_files"`
	Middleware     []string          `json:"middleware"`
}

type StaticFilesConfig

type StaticFilesConfig struct {
	StaticDir string `json:"static_dir"`
	IndexFile string `json:"index_file"`
}

type TLSConfig

type TLSConfig struct {
	CertFile string `json:"cert_file"`
	KeyFile  string `json:"key_file"`
}

type TimeoutsConfig

type TimeoutsConfig struct {
	IdleTimeout           time.Duration `json:"idle_timeout"`
	HeaderTimeout         time.Duration `json:"header_timeout"`
	ResponseHeaderTimeout time.Duration `json:"response_header_timeout"`
}

type TrieNode

type TrieNode struct {
	Children []*TrieNode            `json:"children"`  // Child nodes of the current node.
	Handler  func(ctx *HttpContext) `json:"-"`         // Handler function for the node.
	Level    int                    `json:"level"`     // Depth level of the node in the trie.
	Pattern  string                 `json:"pattern"`   // Pattern of the node.
	NodeType NodeType               `json:"node_type"` // Type of the node (Static, Param, Regex).
	Method   string                 `json:"method"`    // HTTP method associated with the route.
	FullPath string                 `json:"full_path"` // Full path to the node.
	Path     string                 `json:"path"`      // Name of the current node.
}

TrieNode represents a node in the trie.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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