httpserver

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

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

Go to latest
Published: Oct 24, 2025 License: MIT Imports: 12 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoHost                   = errors.New("host cannot be empty")
	ErrInvalidBasePath          = errors.New("base path must be absolute and not end with a slash")
	ErrNoCertFile               = errors.New("key file is set but cert_file is empty")
	ErrNoKeyFile                = errors.New("cert file is set but key_file is empty")
	ErrInvalidReadTimeout       = errors.New("read timeout must be greater than 0")
	ErrInvalidReadHeaderTimeout = errors.New("read header timeout must be greater than 0")
	ErrInvalidPort              = errors.New("port must be a number between 1 and 65535")
)
View Source
var (
	// ColoredStatusCodes is used to set the color and format of HTTP status codes.
	//nolint:gochecknoglobals // This is a lookup map that needs to be globally accessible.
	ColoredStatusCodes = map[int]string{
		http.StatusOK:                            color.GreenString("%d", http.StatusOK),
		http.StatusCreated:                       color.GreenString("%d", http.StatusCreated),
		http.StatusAccepted:                      color.GreenString("%d", http.StatusAccepted),
		http.StatusNonAuthoritativeInfo:          color.GreenString("%d", http.StatusNonAuthoritativeInfo),
		http.StatusNoContent:                     color.GreenString("%d", http.StatusNoContent),
		http.StatusResetContent:                  color.GreenString("%d", http.StatusResetContent),
		http.StatusPartialContent:                color.GreenString("%d", http.StatusPartialContent),
		http.StatusMultiStatus:                   color.GreenString("%d", http.StatusMultiStatus),
		http.StatusAlreadyReported:               color.GreenString("%d", http.StatusAlreadyReported),
		http.StatusIMUsed:                        color.GreenString("%d", http.StatusIMUsed),
		http.StatusMultipleChoices:               color.WhiteString("%d", http.StatusMultipleChoices),
		http.StatusMovedPermanently:              color.WhiteString("%d", http.StatusMovedPermanently),
		http.StatusFound:                         color.WhiteString("%d", http.StatusFound),
		http.StatusSeeOther:                      color.WhiteString("%d", http.StatusSeeOther),
		http.StatusNotModified:                   color.WhiteString("%d", http.StatusNotModified),
		http.StatusUseProxy:                      color.WhiteString("%d", http.StatusUseProxy),
		http.StatusTemporaryRedirect:             color.WhiteString("%d", http.StatusTemporaryRedirect),
		http.StatusPermanentRedirect:             color.WhiteString("%d", http.StatusPermanentRedirect),
		http.StatusBadRequest:                    color.YellowString("%d", http.StatusBadRequest),
		http.StatusUnauthorized:                  color.YellowString("%d", http.StatusUnauthorized),
		http.StatusPaymentRequired:               color.YellowString("%d", http.StatusPaymentRequired),
		http.StatusForbidden:                     color.YellowString("%d", http.StatusForbidden),
		http.StatusNotFound:                      color.YellowString("%d", http.StatusNotFound),
		http.StatusMethodNotAllowed:              color.YellowString("%d", http.StatusMethodNotAllowed),
		http.StatusNotAcceptable:                 color.YellowString("%d", http.StatusNotAcceptable),
		http.StatusProxyAuthRequired:             color.YellowString("%d", http.StatusProxyAuthRequired),
		http.StatusRequestTimeout:                color.YellowString("%d", http.StatusRequestTimeout),
		http.StatusConflict:                      color.YellowString("%d", http.StatusConflict),
		http.StatusGone:                          color.YellowString("%d", http.StatusGone),
		http.StatusLengthRequired:                color.YellowString("%d", http.StatusLengthRequired),
		http.StatusPreconditionFailed:            color.YellowString("%d", http.StatusPreconditionFailed),
		http.StatusRequestEntityTooLarge:         color.YellowString("%d", http.StatusRequestEntityTooLarge),
		http.StatusRequestURITooLong:             color.YellowString("%d", http.StatusRequestURITooLong),
		http.StatusUnsupportedMediaType:          color.YellowString("%d", http.StatusUnsupportedMediaType),
		http.StatusRequestedRangeNotSatisfiable:  color.YellowString("%d", http.StatusRequestedRangeNotSatisfiable),
		http.StatusExpectationFailed:             color.YellowString("%d", http.StatusExpectationFailed),
		http.StatusTeapot:                        color.YellowString("%d", http.StatusTeapot),
		http.StatusMisdirectedRequest:            color.YellowString("%d", http.StatusMisdirectedRequest),
		http.StatusUnprocessableEntity:           color.YellowString("%d", http.StatusUnprocessableEntity),
		http.StatusLocked:                        color.YellowString("%d", http.StatusLocked),
		http.StatusFailedDependency:              color.YellowString("%d", http.StatusFailedDependency),
		http.StatusTooEarly:                      color.YellowString("%d", http.StatusTooEarly),
		http.StatusUpgradeRequired:               color.YellowString("%d", http.StatusUpgradeRequired),
		http.StatusPreconditionRequired:          color.YellowString("%d", http.StatusPreconditionRequired),
		http.StatusTooManyRequests:               color.YellowString("%d", http.StatusTooManyRequests),
		http.StatusRequestHeaderFieldsTooLarge:   color.YellowString("%d", http.StatusRequestHeaderFieldsTooLarge),
		http.StatusUnavailableForLegalReasons:    color.YellowString("%d", http.StatusUnavailableForLegalReasons),
		http.StatusInternalServerError:           color.RedString("%d", http.StatusInternalServerError),
		http.StatusNotImplemented:                color.RedString("%d", http.StatusNotImplemented),
		http.StatusBadGateway:                    color.RedString("%d", http.StatusBadGateway),
		http.StatusServiceUnavailable:            color.RedString("%d", http.StatusServiceUnavailable),
		http.StatusGatewayTimeout:                color.RedString("%d", http.StatusGatewayTimeout),
		http.StatusHTTPVersionNotSupported:       color.RedString("%d", http.StatusHTTPVersionNotSupported),
		http.StatusVariantAlsoNegotiates:         color.RedString("%d", http.StatusVariantAlsoNegotiates),
		http.StatusInsufficientStorage:           color.RedString("%d", http.StatusInsufficientStorage),
		http.StatusLoopDetected:                  color.RedString("%d", http.StatusLoopDetected),
		http.StatusNotExtended:                   color.RedString("%d", http.StatusNotExtended),
		http.StatusNetworkAuthenticationRequired: color.RedString("%d", http.StatusNetworkAuthenticationRequired),
	}

	// ColoredMethods is used to set the color and format of HTTP methods.
	//nolint:gochecknoglobals // This is a lookup map that needs to be globally accessible.
	ColoredMethods = map[string]string{
		http.MethodGet:     color.BlueString(http.MethodGet),
		http.MethodHead:    color.MagentaString(http.MethodHead),
		http.MethodPost:    color.CyanString(http.MethodPost),
		http.MethodPut:     color.YellowString(http.MethodPut),
		http.MethodPatch:   color.GreenString(http.MethodPatch),
		http.MethodDelete:  color.RedString(http.MethodDelete),
		http.MethodConnect: color.WhiteString(http.MethodConnect),
		http.MethodOptions: color.WhiteString(http.MethodOptions),
		http.MethodTrace:   color.WhiteString(http.MethodTrace),
	}
)
View Source
var (
	ErrNoContext = errors.New("context can not be empty")
)

Functions

func NewGinLogger

func NewGinLogger(log logger.Logger) gin.HandlerFunc

NewGinLogger creates a gin.HandlerFunc that logs HTTP request details using the provided logger.

Types

type Config

type Config struct {

	// Host represents network host address.
	Host string `json:"host" yaml:"host" mapstructure:"host"`

	// BasePath represents the prefixed path in the URL.
	BasePath string `json:"base_path" yaml:"base_path" mapstructure:"base_path"`

	// CertFile represents the path to the certificate file.
	CertFile string `json:"cert_file" yaml:"cert_file" mapstructure:"cert_file"`

	// KeyFile represents the path to the key file.
	KeyFile string `json:"key_file" yaml:"key_file" mapstructure:"key_file"`

	// ReadTimeout represents the maximum duration before timing out read of the request.
	ReadTimeout time.Duration `json:"read_timeout" yaml:"read_timeout" mapstructure:"read_timeout"`

	// ReadHeaderTimeout represents the amount of time allowed to read request headers.
	ReadHeaderTimeout time.Duration `json:"read_header_timeout" yaml:"read_header_timeout" mapstructure:"read_header_timeout"`

	// Port specifies the port to be used for connections.
	Port int `json:"port" yaml:"port" mapstructure:"port"`
}

Config defines the essential parameters for serving an http server.

func (*Config) SetDefaults

func (r *Config) SetDefaults()

SetDefaults initializes the default values for the relevant fields in the struct.

func (*Config) Validate

func (r *Config) Validate() error

Validate ensures the all necessary configurations are filled and within valid confines.

type HTTPServer

type HTTPServer struct {

	// Engine is an instance from the Gin web framework for Go to handle HTTP requests.
	Engine *gin.Engine

	// Router is a router group from Gin that allows setting a base path for all routes.
	Router *gin.RouterGroup
	// contains filtered or unexported fields
}

HTTPServer encapsulates an HTTP server with some additional features.

func New

func New(config *Config, log logger.ConfigurableLogger) *HTTPServer

New creates a new instance of HTTPServer with the given configuration.

func (*HTTPServer) SetEngine

func (r *HTTPServer) SetEngine(engine *gin.Engine)

func (*HTTPServer) Start

func (r *HTTPServer) Start(ctx context.Context, done func()) error

Start function starts the HTTP server in a separate goroutine.

func (*HTTPServer) Stop

func (r *HTTPServer) Stop()

Stop function stops the HTTP server gracefully within a second time limit.

type LogEntry

type LogEntry struct {
	ClientIP   string        `json:"client-ip"`
	Errors     string        `json:"errors"`
	Method     string        `json:"method"`
	Path       string        `json:"path"`
	Latency    time.Duration `json:"latency"`
	Size       int           `json:"size"`
	StatusCode int           `json:"status-code"`
}

LogEntry represents a single log entry with details about an HTTP request.

func (*LogEntry) MethodColor

func (r *LogEntry) MethodColor() string

MethodColor returns the HTTP method of the log entry as a colored string.

func (*LogEntry) StatusCodeColor

func (r *LogEntry) StatusCodeColor() string

StatusCodeColor returns the status code of the log entry as a colored string.

func (*LogEntry) String

func (r *LogEntry) String() string

String formats the LogEntry into a human-readable string with colored status code and method.

Jump to

Keyboard shortcuts

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