mhttp

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2025 License: MIT Imports: 39 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DefaultServerName = "default"
)
View Source
const (
	ResponseKey contextKey = "MaltoseResponse"
)

Variables

View Source
var LogMaxBodySize = -1

Functions

This section is empty.

Types

type Config added in v0.1.2

type Config struct {
	// Address is the address of the server.
	Address string `mconv:"address"`
	// ServerName is the name of the server.
	ServerName string `mconv:"server_name"`
	// ServerRoot is the root directory of the server.
	ServerRoot string `mconv:"server_root"`
	// ServerLocale is the locale of the server.
	ServerLocale string `mconv:"server_locale"`
	// ReadTimeout is the timeout for reading the request.
	ReadTimeout time.Duration `mconv:"read_timeout"`
	// WriteTimeout is the timeout for writing the response.
	WriteTimeout time.Duration `mconv:"write_timeout"`
	// IdleTimeout is the timeout for idle connections.
	IdleTimeout time.Duration `mconv:"idle_timeout"`
	// MaxHeaderBytes is the maximum number of bytes in the request header.
	MaxHeaderBytes int `mconv:"max_header_bytes"`
	// HealthCheck is the health check config.
	HealthCheck string `mconv:"health_check"`
	// TLSEnable is the tls config.
	TLSEnable bool `mconv:"tls_enable"`
	// TLSCertFile is the path to the tls certificate file.
	TLSCertFile string `mconv:"tls_cert_file"`
	// TLSKeyFile is the path to the tls key file.
	TLSKeyFile string `mconv:"tls_key_file"`
	// TLSServerName is the server name for tls.
	TLSServerName string `mconv:"tls_server_name"`
	// GracefulEnable is the graceful shutdown config.
	GracefulEnable bool `mconv:"graceful_enable"`
	// GracefulTimeout is the timeout for graceful shutdown.
	GracefulTimeout time.Duration `mconv:"graceful_timeout"`
	// GracefulWaitTime is the wait time for graceful shutdown.
	GracefulWaitTime time.Duration `mconv:"graceful_wait_time"`
	// OpenapiPath is the path to the openapi file.
	OpenapiPath string `mconv:"openapi_path"`
	// SwaggerPath is the path to the swagger file.
	SwaggerPath string `mconv:"swagger_path"`
	// SwaggerTemplate is the template for the swagger file.
	SwaggerTemplate string `mconv:"swagger_template"`
	// PrintRoutes is the print routes config.
	PrintRoutes bool `mconv:"print_routes"`
	// Logger is the logger config.
	Logger *mlog.Logger
}

Config is the server configuration.

func ConfigFromMap added in v0.1.2

func ConfigFromMap(configMap map[string]any) (*Config, error)

ConfigFromMap creates a new server config from a map.

func (*Config) SetConfigWithMap added in v0.1.2

func (c *Config) SetConfigWithMap(configMap map[string]any) error

SetConfigWithMap sets the server config.

type DefaultResponse

type DefaultResponse struct {
	Code    int    `json:"code"`    // business code
	Message string `json:"message"` // prompt information
	Data    any    `json:"data"`    // business data
}

DefaultResponse standard response structure

type HandlerFunc

type HandlerFunc func(*Request)

HandlerFunc defines the basic handler function type.

type MiddlewareFunc

type MiddlewareFunc func(*Request)

MiddlewareFunc defines the middleware function type.

func MiddlewareLog

func MiddlewareLog() MiddlewareFunc

MiddlewareLog is a middleware for logging HTTP requests in two steps: 1. Before the handler is executed ("started"). 2. After the handler is completed ("finished"). This allows for better observability, especially for hanging or panicking requests.

func MiddlewareRateLimit

func MiddlewareRateLimit(config RateLimitConfig) MiddlewareFunc

MiddlewareRateLimit creates a middleware that implements rate limiting using a token bucket algorithm

func MiddlewareRateLimitByIP

func MiddlewareRateLimitByIP(config RateLimitConfig) MiddlewareFunc

MiddlewareRateLimitByIP creates a middleware that implements rate limiting per IP address

func MiddlewareResponse

func MiddlewareResponse() MiddlewareFunc

MiddlewareResponse standard response middleware

type RateLimitConfig

type RateLimitConfig struct {
	// Rate defines the number of requests allowed per second
	Rate float64
	// Burst defines the maximum number of requests that can be processed at once
	Burst int
	// SkipFunc is an optional function to determine if rate limiting should be skipped
	SkipFunc func(*Request) bool
	// ErrorHandler is an optional function to handle rate limit errors
	ErrorHandler func(*Request)
}

RateLimitConfig defines the configuration for rate limiting

func DefaultRateLimitConfig

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns a default rate limit configuration

type Request

type Request struct {
	*gin.Context
	// contains filtered or unexported fields
}

Request is the request wrapper.

func RequestFromCtx

func RequestFromCtx(ctx context.Context) *Request

RequestFromCtx gets the Request object from the context.

func (*Request) Conf added in v0.1.17

func (r *Request) Conf() *Config

Conf gets the server config.

func (*Request) Error

func (r *Request) Error(err error) *Request

Error adds an error message.

func (*Request) GetHandlerResponse

func (r *Request) GetHandlerResponse() any

GetHandlerResponse gets the handler response.

func (*Request) GetServerName

func (r *Request) GetServerName() string

GetServerName gets the server name.

func (*Request) GetTranslator

func (r *Request) GetTranslator() ut.Translator

GetTranslator gets the translator.

func (*Request) Logger

func (r *Request) Logger() *mlog.Logger

Logger gets the logger instance.

func (*Request) SetHandlerResponse

func (r *Request) SetHandlerResponse(res any)

SetHandlerResponse sets the handler response.

type Route

type Route struct {
	Method           string
	Path             string
	HandlerFunc      HandlerFunc
	Type             routeType
	Controller       any            // controller object
	ControllerMethod reflect.Method // controller method
	ReqType          reflect.Type   // request parameter type
	RespType         reflect.Type   // response type
}

Route is the route information.

type RouterGroup

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

RouterGroup is the router group for the server.

func (*RouterGroup) Any

func (rg *RouterGroup) Any(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

Any registers all HTTP methods route.

func (*RouterGroup) Bind

func (rg *RouterGroup) Bind(object ...any) *RouterGroup

Bind binds the controller object.

func (*RouterGroup) DELETE

func (rg *RouterGroup) DELETE(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

DELETE registers DELETE request route.

func (*RouterGroup) GET

func (rg *RouterGroup) GET(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

GET registers GET request route.

func (*RouterGroup) Group

func (rg *RouterGroup) Group(path string, handlers ...RouterGroupOption) *RouterGroup

Group creates a new router group.

func (*RouterGroup) HEAD

func (rg *RouterGroup) HEAD(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

HEAD registers HEAD request route.

func (*RouterGroup) Handle

func (rg *RouterGroup) Handle(method, path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

Handle is a general route registration method.

func (*RouterGroup) Middleware

func (rg *RouterGroup) Middleware(middlewares ...MiddlewareFunc) *RouterGroup

Middleware adds middlewares.

func (*RouterGroup) OPTIONS

func (rg *RouterGroup) OPTIONS(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

OPTIONS registers OPTIONS request route.

func (*RouterGroup) PATCH

func (rg *RouterGroup) PATCH(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

PATCH registers PATCH request route.

func (*RouterGroup) POST

func (rg *RouterGroup) POST(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

POST registers POST request route.

func (*RouterGroup) PUT

func (rg *RouterGroup) PUT(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *RouterGroup

PUT registers PUT request route.

func (*RouterGroup) Use

func (rg *RouterGroup) Use(middlewares []MiddlewareFunc, handlers ...RouterGroupOption) *RouterGroup

Use adds middlewares.

type RouterGroupOption

type RouterGroupOption func(*RouterGroup)

type RuleFunc

type RuleFunc func(fl validator.FieldLevel) bool

RuleFunc is the custom validation rule function.

type Server

type Server struct {
	RouterGroup
	// contains filtered or unexported fields
}

Server HTTP server structure.

func New

func New(config ...*Config) *Server

New creates a new HTTP server.

func (*Server) EnablePProf

func (s *Server) EnablePProf(pattern ...string)

EnablePProf enables PProf functionality for the server

func (*Server) Middleware

func (s *Server) Middleware(middlewares ...MiddlewareFunc)

Middleware alias Use.

func (*Server) RegisterRuleWithTranslation

func (s *Server) RegisterRuleWithTranslation(rule string, fn RuleFunc, errMessage map[string]string)

RegisterRuleWithTranslation registers the custom validation rule and translation for multiple languages.

func (*Server) Routes

func (s *Server) Routes() []Route

func (*Server) Run

func (s *Server) Run()

Run starts the HTTP server.

func (*Server) SetAddress

func (s *Server) SetAddress(addr string)

SetAddress sets the server listening address.

func (*Server) SetConfig added in v0.1.4

func (s *Server) SetConfig(config *Config)

func (*Server) SetConfigWithMap

func (s *Server) SetConfigWithMap(configMap map[string]any) error

SetConfigWithMap sets the server config.

func (*Server) SetLogger

func (s *Server) SetLogger(logger *mlog.Logger)

SetLogger sets the logger instance.

func (*Server) SetNoRouteHandler added in v0.1.19

func (s *Server) SetNoRouteHandler(handler HandlerFunc)

func (*Server) SetServerName

func (s *Server) SetServerName(name string)

SetServerName sets the server name.

func (*Server) SetStaticPath

func (s *Server) SetStaticPath(prefix string, directory string)

SetStaticPath enhances the static file service.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

func (*Server) Use

func (s *Server) Use(middlewares ...MiddlewareFunc)

Use adds global middleware.

func (*Server) WithPanicHandler added in v0.2.0

func (s *Server) WithPanicHandler(handler func(r *Request, err error)) *Server

WithPanicHandler sets a custom panic handler for the server

Jump to

Keyboard shortcuts

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