{"modulePath":"github.com/acronis/go-appkit","version":"v1.38.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpserver\n\nPackage httpserver provides preconfigured and ready-to-use in production HTTP server.\n\n## Constants\n\n```go\nconst StatusClientClosedRequest = 499\n```\nStatusClientClosedRequest is a special HTTP status code used by Nginx to show that the client closed the request before the server could send a response\n\n## Functions\n\n```go\nfunc GetChiRoutePattern(r *http.Request) string\n```\nGetChiRoutePattern extracts chi route pattern from request.\n\n```go\nfunc NewRouter(logger log.FieldLogger, opts RouterOpts) chi.Router\n```\nNewRouter creates a new chi.Router and performs its basic configuration.\n\n## Types\n\n```go\ntype APIRoute = func(router chi.Router)\n```\nAPIRoute is a type alias for single API route.\n\n```go\ntype APIVersion = int\n```\nAPIVersion is a type alias for API version.\n\n```go\ntype Config struct {\n\tAddress        string         `mapstructure:\"address\" yaml:\"address\" json:\"address\"`\n\tUnixSocketPath string         `mapstructure:\"unixSocketPath\" yaml:\"unixSocketPath\" json:\"unixSocketPath\"`\n\tTimeouts       TimeoutsConfig `mapstructure:\"timeouts\" yaml:\"timeouts\" json:\"timeouts\"`\n\tLimits         LimitsConfig   `mapstructure:\"limits\" yaml:\"limits\" json:\"limits\"`\n\tLog            LogConfig      `mapstructure:\"log\" yaml:\"log\" json:\"log\"`\n\tTLS            TLSConfig      `mapstructure:\"tls\" yaml:\"tls\" json:\"tls\"`\n\t// contains filtered or unexported fields\n}\n```\nConfig represents a set of configuration parameters for HTTPServer. Configuration can be loaded in different formats (YAML, JSON) using config.Loader, viper, or with json.Unmarshal/yaml.Unmarshal functions directly.\n\n```go\nfunc NewConfig(options ...ConfigOption) *Config\n```\nNewConfig creates a new instance of the Config.\n\n```go\nfunc NewConfigWithKeyPrefix(keyPrefix string) *Config\n```\nNewConfigWithKeyPrefix creates a new instance of the Config with a key prefix. This prefix will be used by config.Loader.\n\nDeprecated: use NewConfig with WithKeyPrefix instead.\n\n```go\nfunc NewDefaultConfig(options ...ConfigOption) *Config\n```\nNewDefaultConfig creates a new instance of the Config with default values.\n\n```go\nfunc (c *Config) KeyPrefix() string\n```\nKeyPrefix returns a key prefix with which all configuration parameters should be presented. Implements config.KeyPrefixProvider interface.\n\n```go\nfunc (c *Config) Set(dp config.DataProvider) error\n```\nSet sets HTTPServer configuration values from config.DataProvider.\n\n```go\nfunc (c *Config) SetProviderDefaults(dp config.DataProvider)\n```\nSetProviderDefaults sets default configuration values for HTTPServer in config.DataProvider. Implements config.Config interface.\n\n```go\ntype ConfigOption func(*configOptions)\n```\nConfigOption is a type for functional options for the Config.\n\n```go\nfunc WithKeyPrefix(keyPrefix string) ConfigOption\n```\nWithKeyPrefix returns a ConfigOption that sets a key prefix for parsing configuration parameters. This prefix will be used by config.Loader.\n\n```go\ntype HTTPRequestMetricsOpts struct {\n\t// Metrics opts.\n\tNamespace        string\n\tDurationBuckets  []float64\n\tConstLabels      prometheus.Labels\n\tCustomLabelNames []string\n\n\t// Middleware opts.\n\t//\n\t// Deprecated: GetUserAgentType be removed in the next major version. Please use CustomLabels with Context instead.\n\tGetUserAgentType middleware.UserAgentTypeGetterFunc\n\tGetRoutePattern  middleware.RoutePatternGetterFunc\n}\n```\nHTTPRequestMetricsOpts represents options for HTTPRequestMetricsOpts middleware that used in HTTPServer.\n\n```go\ntype HTTPServer struct {\n\t// TODO: URL does not contain port when port is dynamically chosen\n\tURL             string\n\tHTTPServer      *http.Server\n\tUnixSocketPath  string\n\tTLS             TLSConfig\n\tHTTPRouter      chi.Router\n\tLogger          log.FieldLogger\n\tShutdownTimeout time.Duration\n\t// contains filtered or unexported fields\n}\n```\nHTTPServer represents a wrapper around http.Server with additional fields and methods. chi.Router is used as a handler for the server by default. It also implements service.Unit and service.MetricsRegisterer interfaces.\n\n```go\nfunc New(cfg *Config, logger log.FieldLogger, opts Opts) (*HTTPServer, error)\n```\nNew creates a new HTTPServer with predefined logging, metrics collecting, recovering after panics and health-checking functionality.\n\n```go\nfunc NewWithHandler(cfg *Config, logger log.FieldLogger, handler http.Handler) *HTTPServer\n```\nNewWithHandler creates a new HTTPServer receiving already created http.Handler. Unlike the New constructor, it doesn't add any middlewares. Typical use case: create a chi.Router using NewRouter and pass it into NewWithHandler.\n\nDeprecated: Will be removed in the next major version. Please use New with Handler options instead.\n\n```go\nfunc (s *HTTPServer) GetPort() int\n```\n\n```go\nfunc (s *HTTPServer) MustRegisterMetrics()\n```\nMustRegisterMetrics registers metrics in Prometheus client and panics if any error occurs.\n\n```go\nfunc (s *HTTPServer) NetworkAndAddr() (network string, addr string)\n```\nNetworkAndAddr returns network type (\"tcp\" or \"unix\") and address (path to unix socket in case of \"unix\" network).\n\n```go\nfunc (s *HTTPServer) Start(fatalError chan\u003c- error)\n```\nStart starts application HTTP server in a blocking way. It's supposed that this method will be called in a separate goroutine. If a fatal error occurs, it will be sent to the fatalError channel.\n\n```go\nfunc (s *HTTPServer) Stop(gracefully bool) error\n```\nStop stops application HTTP server (gracefully or not).\n\n```go\nfunc (s *HTTPServer) UnregisterMetrics()\n```\nUnregisterMetrics unregisters metrics in Prometheus client.\n\n```go\ntype HealthCheck = func() (HealthCheckResult, error)\n```\nHealthCheck is a type alias for health-check operation. It's used for better readability.\n\n```go\ntype HealthCheckComponentName = string\n```\nHealthCheckComponentName is a type alias for component names. It's used for better readability.\n\n```go\ntype HealthCheckContext = func(ctx context.Context) (HealthCheckResult, error)\n```\nHealthCheckContext is a type alias for health-check operation that has access to the request Context\n\n```go\ntype HealthCheckHandler struct {\n\t// contains filtered or unexported fields\n}\n```\nHealthCheckHandler implements http.Handler and does health-check of a service.\n\n```go\nfunc NewHealthCheckHandler(fn HealthCheck) *HealthCheckHandler\n```\nNewHealthCheckHandler creates a new http.Handler for doing health-check. Passing function will be called inside handler and should return statuses of service's components.\n\n```go\nfunc NewHealthCheckHandlerContext(fn HealthCheckContext) *HealthCheckHandler\n```\nNewHealthCheckHandlerContext creates a new http.Handler for doing health-check. It is able to access the request Context. Passing function will be called inside handler and should return statuses of service's components.\n\n```go\nfunc (h *HealthCheckHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request)\n```\nServeHTTP serves heath-check HTTP request.\n\n```go\ntype HealthCheckResult = map[HealthCheckComponentName]HealthCheckStatus\n```\nHealthCheckResult is a type alias for result of health-check operation. It's used for better readability.\n\n```go\ntype HealthCheckStatus int\n```\nHealthCheckStatus is a resulting status of the health-check.\n\n```go\nconst (\n\tHealthCheckStatusOK HealthCheckStatus = iota\n\tHealthCheckStatusFail\n)\n```\nHealth-check statuses.\n\n```go\ntype LimitsConfig struct {\n\t// MaxRequests is the maximum number of requests that can be processed concurrently.\n\tMaxRequests int `mapstructure:\"maxRequests\" yaml:\"maxRequests\" json:\"maxRequests\"`\n\n\t// MaxBodySizeBytes is the maximum size of the request body in bytes.\n\tMaxBodySizeBytes config.ByteSize `mapstructure:\"maxBodySize\" yaml:\"maxBodySize\" json:\"maxBodySize\"`\n}\n```\nLimitsConfig represents a set of configuration parameters for HTTPServer relating to limits.\n\n```go\nfunc (l *LimitsConfig) Set(dp config.DataProvider) error\n```\nSet sets limit server configuration values from config.DataProvider.\n\n```go\ntype LogConfig struct {\n\tRequestStart           bool                `mapstructure:\"requestStart\" yaml:\"requestStart\" json:\"requestStart\"`\n\tRequestHeaders         []string            `mapstructure:\"requestHeaders\" yaml:\"requestHeaders\" json:\"requestHeaders\"`\n\tExcludedEndpoints      []string            `mapstructure:\"excludedEndpoints\" yaml:\"excludedEndpoints\" json:\"excludedEndpoints\"`\n\tSecretQueryParams      []string            `mapstructure:\"secretQueryParams\" yaml:\"secretQueryParams\"`\n\tAddRequestInfoToLogger bool                `mapstructure:\"addRequestInfo\" yaml:\"addRequestInfo\" json:\"addRequestInfo\"`\n\tSlowRequestThreshold   config.TimeDuration `mapstructure:\"slowRequestThreshold\" yaml:\"slowRequestThreshold\" json:\"slowRequestThreshold\"`\n\tTimeSlotsThreshold     config.TimeDuration `mapstructure:\"timeSlotsThreshold\" yaml:\"timeSlotsThreshold\" json:\"timeSlotsThreshold\"`\n}\n```\nLogConfig represents a set of configuration parameters for HTTPServer relating to logging.\n\n```go\nfunc (l *LogConfig) Set(dp config.DataProvider) error\n```\nSet sets log server configuration values from config.DataProvider.\n\n```go\ntype Opts struct {\n\t// ServiceNameInURL is a prefix for API routes (e.g., \"/api/service_name/v1\").\n\tServiceNameInURL string\n\t// APIRoutes is a map of API versions to their route configuration functions.\n\tAPIRoutes map[APIVersion]APIRoute\n\t// RootMiddlewares is a list of middlewares to be applied to the root router.\n\tRootMiddlewares []func(http.Handler) http.Handler\n\t// ErrorDomain is used for error response formatting.\n\tErrorDomain string\n\t// HealthCheck is a function that performs health check logic.\n\tHealthCheck HealthCheck\n\t// HealthCheckContext is a function that performs context-aware health check logic.\n\tHealthCheckContext HealthCheckContext\n\t// MetricsHandler is a custom handler for the /metrics endpoint (e.g., Prometheus handler).\n\tMetricsHandler http.Handler\n\t// HTTPRequestMetrics contains options for configuring HTTP request metrics middleware.\n\tHTTPRequestMetrics HTTPRequestMetricsOpts\n\t// Handler is a custom HTTP handler to use instead of the default router with middlewares.\n\t// When provided, default middlewares are not applied.\n\tHandler http.Handler\n\t// Listener is a pre-configured network listener to use instead of creating a new one.\n\t// Useful for custom listener configurations or testing with mock listeners.\n\tListener net.Listener\n}\n```\nOpts represents options for creating HTTPServer.\n\n```go\ntype RouterOpts struct {\n\tServiceNameInURL   string\n\tAPIRoutes          map[APIVersion]APIRoute\n\tRootMiddlewares    []func(http.Handler) http.Handler\n\tErrorDomain        string\n\tHealthCheck        HealthCheck\n\tHealthCheckContext HealthCheckContext\n\tMetricsHandler     http.Handler\n}\n```\nRouterOpts represents options for creating chi.Router.\n\n```go\ntype TLSConfig struct {\n\tEnabled     bool   `mapstructure:\"enabled\" yaml:\"enabled\" json:\"enabled\"`\n\tCertificate string `mapstructure:\"cert\" yaml:\"cert\" json:\"cert\"`\n\tKey         string `mapstructure:\"key\" yaml:\"key\" json:\"key\"`\n}\n```\nTLSConfig contains configuration parameters needed to initialize (or not) secure server\n\n```go\nfunc (s *TLSConfig) Set(dp config.DataProvider) error\n```\nSet sets security server configuration values from config.DataProvider.\n\n```go\ntype TimeoutsConfig struct {\n\tWrite      config.TimeDuration `mapstructure:\"write\" yaml:\"write\" json:\"write\"`\n\tRead       config.TimeDuration `mapstructure:\"read\" yaml:\"read\" json:\"read\"`\n\tReadHeader config.TimeDuration `mapstructure:\"readHeader\" yaml:\"readHeader\" json:\"readHeader\"`\n\tIdle       config.TimeDuration `mapstructure:\"idle\" yaml:\"idle\" json:\"idle\"`\n\tShutdown   config.TimeDuration `mapstructure:\"shutdown\" yaml:\"shutdown\" json:\"shutdown\"`\n}\n```\nTimeoutsConfig represents a set of configuration parameters for HTTPServer relating to timeouts.\n\n```go\nfunc (t *TimeoutsConfig) Set(dp config.DataProvider) error\n```\nSet sets timeout server configuration values from config.DataProvider. Implements config.Config interface.\n\n","path":"github.com/acronis/go-appkit/httpserver","name":"httpserver","synopsis":"Package httpserver provides preconfigured and ready-to-use in production HTTP server.","isRedistributable":true}
