httpfx

package
v0.6.25 Latest Latest
Warning

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

Go to latest
Published: May 21, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

README

ajan/httpfx

Overview

The httpfx package provides a framework for building HTTP services with support for routing, middleware, and OpenAPI documentation generation. The package is designed to work seamlessly with the ajan/di package.

The documentation below provides an overview of the package, its types, functions, and usage examples. For more detailed information, refer to the source code and tests.

Configuration

Configuration struct for the HTTP service:

type Config struct {
	Addr string `conf:"ADDR" default:":8080"`

	CertString        string        `conf:"CERT_STRING"`
	KeyString         string        `conf:"KEY_STRING"`
	ReadHeaderTimeout time.Duration `conf:"READ_HEADER_TIMEOUT" default:"5s"`
	ReadTimeout       time.Duration `conf:"READ_TIMEOUT"        default:"10s"`
	WriteTimeout      time.Duration `conf:"WRITE_TIMEOUT"       default:"10s"`
	IdleTimeout       time.Duration `conf:"IDLE_TIMEOUT"        default:"120s"`

	InitializationTimeout   time.Duration `conf:"INIT_TIMEOUT"     default:"25s"`
	GracefulShutdownTimeout time.Duration `conf:"SHUTDOWN_TIMEOUT" default:"5s"`

	SelfSigned bool `conf:"SELF_SIGNED" default:"false"`

	HealthCheckEnabled bool `conf:"HEALTH_CHECK" default:"true"`
	OpenApiEnabled     bool `conf:"OPENAPI"      default:"true"`
	ProfilingEnabled   bool `conf:"PROFILING"    default:"false"`
}

Example configuration:

config := &httpfx.Config{
	Addr:            ":8080",
	ReadTimeout:     15 * time.Second,
	WriteTimeout:    15 * time.Second,
	IdleTimeout:     60 * time.Second,
	OpenApiEnabled:  true,
	SelfSigned:      false,
}

API

NewRouter function

Create a new Router object.

// func NewRouter(path string) *RouterImpl

router := httpfx.NewRouter("/")
NewHttpService function

Creates a new HttpService object based on the provided configuration.

// func NewHttpService(config *Config, router Router) *HttpServiceImpl

router := httpfx.NewRouter("/")
hs := httpfx.NewHttpService(config, router)

Features

  • HTTP routing with support for path parameters and wildcards
  • Middleware support for request/response processing
  • OpenAPI documentation generation
  • Graceful shutdown handling
  • Configurable timeouts and server settings
  • Integration with dependency injection
  • Support for CORS and security headers
  • Request logging and metrics

Example Usage

func main() {
	// Create router
	router := httpfx.NewRouter("/api")

	// Add routes
	router.Get("/health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("OK"))
	})

	// Add middleware
	router.Use(httpfx.LoggerMiddleware())
	router.Use(httpfx.RecoveryMiddleware())

	// Create and start service
	config := &httpfx.Config{
		Addr: ":8080",
	}
	service := httpfx.NewHttpService(config, router)

	if err := service.Start(); err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Addr string `conf:"ADDR" default:":8080"`

	CertString        string        `conf:"CERT_STRING"`
	KeyString         string        `conf:"KEY_STRING"`
	ReadHeaderTimeout time.Duration `conf:"READ_HEADER_TIMEOUT" default:"5s"`
	ReadTimeout       time.Duration `conf:"READ_TIMEOUT"        default:"10s"`
	WriteTimeout      time.Duration `conf:"WRITE_TIMEOUT"       default:"10s"`
	IdleTimeout       time.Duration `conf:"IDLE_TIMEOUT"        default:"120s"`

	InitializationTimeout   time.Duration `conf:"INIT_TIMEOUT"     default:"25s"`
	GracefulShutdownTimeout time.Duration `conf:"SHUTDOWN_TIMEOUT" default:"5s"`

	SelfSigned bool `conf:"SELF_SIGNED" default:"false"`

	HealthCheckEnabled bool `conf:"HEALTH_CHECK" default:"true"`
	OpenApiEnabled     bool `conf:"OPENAPI"      default:"true"`
	ProfilingEnabled   bool `conf:"PROFILING"    default:"false"`
}

type Context

type Context struct {
	Request        *http.Request
	ResponseWriter http.ResponseWriter

	Results Results
	// contains filtered or unexported fields
}

func (*Context) Next

func (c *Context) Next() Result

func (*Context) UpdateContext

func (c *Context) UpdateContext(ctx context.Context)

type ContextKey

type ContextKey string

type Handler

type Handler func(*Context) Result

type HandlerChain

type HandlerChain []Handler

type HttpService

type HttpService struct {
	InnerServer  *http.Server
	InnerRouter  *Router
	InnerMetrics *Metrics

	Config *Config
	// contains filtered or unexported fields
}

func NewHttpService

func NewHttpService(
	config *Config,
	router *Router,
	metricsProvider MetricsProvider,
	logger *logfx.Logger,
) *HttpService

func (*HttpService) Router

func (hs *HttpService) Router() *Router

func (*HttpService) Server

func (hs *HttpService) Server() *http.Server

func (*HttpService) Start

func (hs *HttpService) Start(ctx context.Context) (func(), error)

type Metrics

type Metrics struct {
	RequestsTotal *prometheus.CounterVec
	// contains filtered or unexported fields
}

func NewMetrics

func NewMetrics(mp MetricsProvider) *Metrics

type MetricsProvider

type MetricsProvider interface {
	GetRegistry() *prometheus.Registry
}

type Middleware

type Middleware func() Handler

type Result

type Result struct {
	InnerRedirectToUri string
	results.Result

	InnerBody []byte

	InnerStatusCode int
}

func (Result) Body

func (r Result) Body() []byte

func (Result) RedirectToUri

func (r Result) RedirectToUri() string

func (Result) StatusCode

func (r Result) StatusCode() int

func (Result) WithBody

func (r Result) WithBody(body string) Result

func (Result) WithStatusCode

func (r Result) WithStatusCode(statusCode int) Result

type Results

type Results struct{}

func (*Results) Abort

func (r *Results) Abort() Result

func (*Results) BadRequest

func (r *Results) BadRequest() Result

func (*Results) Bytes

func (r *Results) Bytes(body []byte) Result

func (*Results) Error

func (r *Results) Error(statusCode int, message []byte) Result

func (*Results) Json

func (r *Results) Json(body any) Result

func (*Results) NotFound

func (r *Results) NotFound() Result

func (*Results) Ok

func (r *Results) Ok() Result

func (*Results) PlainText

func (r *Results) PlainText(body []byte) Result

func (*Results) Redirect

func (r *Results) Redirect(uri string) Result

func (*Results) Unauthorized

func (r *Results) Unauthorized(body []byte) Result

type Route

type Route struct {
	Pattern        *uris.Pattern
	Parameters     []RouterParameter
	Handlers       []Handler
	MuxHandlerFunc func(http.ResponseWriter, *http.Request)

	Spec RouteOpenApiSpec
}

func (*Route) HasDescription

func (r *Route) HasDescription(description string) *Route

func (*Route) HasOperationId

func (r *Route) HasOperationId(operationId string) *Route

func (*Route) HasPathParameter

func (r *Route) HasPathParameter(name string, description string) *Route

func (*Route) HasQueryParameter

func (r *Route) HasQueryParameter(name string, description string) *Route

func (*Route) HasRequestModel

func (r *Route) HasRequestModel(model any) *Route

func (*Route) HasResponse

func (r *Route) HasResponse(statusCode int) *Route

func (*Route) HasResponseModel

func (r *Route) HasResponseModel(statusCode int, model any) *Route

func (*Route) HasSummary

func (r *Route) HasSummary(summary string) *Route

func (*Route) HasTags

func (r *Route) HasTags(tags ...string) *Route

func (*Route) IsDeprecated

func (r *Route) IsDeprecated() *Route

type RouteOpenApiSpec

type RouteOpenApiSpec struct {
	OperationId string
	Summary     string
	Description string
	Tags        []string

	Requests   []RouteOpenApiSpecRequest
	Responses  []RouteOpenApiSpecResponse
	Deprecated bool
}

type RouteOpenApiSpecRequest

type RouteOpenApiSpecRequest struct {
	Model any
}

type RouteOpenApiSpecResponse

type RouteOpenApiSpecResponse struct {
	Model      any
	StatusCode int
	HasModel   bool
}

type RouteParameterType added in v0.6.17

type RouteParameterType int
const (
	RouteParameterTypeHeader RouteParameterType = iota
	RouteParameterTypeQuery
	RouteParameterTypePath
	RouteParameterTypeBody
)

type Router

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

func NewRouter

func NewRouter(path string) *Router

func (*Router) GetHandlers

func (r *Router) GetHandlers() []Handler

func (*Router) GetMux

func (r *Router) GetMux() *http.ServeMux

func (*Router) GetPath

func (r *Router) GetPath() string

func (*Router) GetRoutes

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

func (*Router) Group

func (r *Router) Group(path string) *Router

func (*Router) Route

func (r *Router) Route(pattern string, handlers ...Handler) *Route

func (*Router) Use

func (r *Router) Use(handlers ...Handler)

type RouterParameter added in v0.6.17

type RouterParameter struct {
	Name        string
	Description string
	Validators  []RouterParameterValidator
	Type        RouteParameterType
	IsRequired  bool
}

type RouterParameterValidator added in v0.6.17

type RouterParameterValidator func(inputString string) (string, error)

Directories

Path Synopsis
modules

Jump to

Keyboard shortcuts

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