httpserver

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-kit/server/http

Go Reference GitHub Release GoCard GitHub license

Пакет для сборки HTTP-сервера.

Использование

import httpserver "github.com/LeKovr/go-kit/server/http"

srv := httpserver.New(cfg.HTTP).WithStatic(files).WithVersion(version)
srv.Use(middleware)
err := srv.Run(ctx)

Defaults применяет config.Open. Run допускает один запуск и закрывает listener. Для обработки SIGINT/SIGTERM используйте server с WithShutdown(srv.Shutdown), как в примере.

При отмене контекста Run или ошибке обслуживания соединения закрываются принудительно. Shutdown(ctx) ждёт завершения активных запросов до истечения переданного контекста, затем принудительно закрывает соединения. Обработчик, игнорирующий отмену контекста, может продолжить работу после возврата Run.

Использование пакета добавляет в сервис следующие опции:

HTTP Options:
      --http.listen=              Addr and port which server listens at (default: :8080) [$HTTP_LISTEN]
      --http.maxheader=           MaxHeaderBytes
      --http.rto=                 HTTP read timeout (default: 10s)
      --http.wto=                 HTTP write timeout, '0' means disable (default: 60s)
      --http.rhto=                HTTP read header timeout (default: 10s)
      --http.ito=                 HTTP idle timeout (default: 10s)
      --http.ip_header=           HTTP Request Header for remote IP (default: X-Real-IP) [$HTTP_IP_HEADER]
      --http.user_header=         HTTP Request Header for username (default: X-Username) [$HTTP_USER_HEADER]
      --http.access_log=          HTTP access log filename (default: STDOUT, '-' means disable) [$HTTP_ACCESS_LOG]
      --http.etag                 Add ETAG in HTTP response [$HTTP_ETAG]
      --http.etag_max_body_bytes= Maximum response body size buffered for ETag; non-positive means 1 MiB (default: 1048576) [$HTTP_ETAG_MAX_BODY_BYTES]

HTTPS Options:
      --http.tls.cert=            CertFile for serving HTTPS instead HTTP [$HTTP_TLS_CERT]
      --http.tls.key=             KeyFile for serving HTTPS instead HTTP [$HTTP_TLS_KEY]
      --http.tls.no-check         disable tls certificate validation

Version response Options:
      --http.vr.prefix=           URL for version response (default: /js/version.js)
      --http.vr.format=           Format string for version response (default: "document.addEventListener('DOMContentLoaded', () => { appVersion.innerText = '%s'; });\n")
      --http.vr.ctype=            js code Content-Type header (default: text/javascript)

Help Options:
  -h, --help                     Show this help message

Documentation

Index

Constants

View Source
const AccessLogDisabled = "-"

AccessLogDisabled holds access_log value for access logging disabling.

View Source
const DefaultETagMaxBodyBytes = 1 << 20

DefaultETagMaxBodyBytes is the default response size limit for automatic ETag generation. Larger responses are streamed without a generated ETag.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Listen string `long:"listen" default:":8080" description:"Addr and port which server listens at" env:"LISTEN"`

	MaxHeaderBytes    int           `long:"maxheader" description:"MaxHeaderBytes"`
	ReadTimeout       time.Duration `long:"rto" default:"10s" description:"HTTP read timeout"`
	WriteTimeout      time.Duration `long:"wto" default:"60s" description:"HTTP write timeout, '0' means disable"`
	ReadHeaderTimeout time.Duration `long:"rhto" default:"10s" description:"HTTP read header timeout"`
	IdleTimeout       time.Duration `long:"ito" default:"10s" description:"HTTP idle timeout"`

	IPHeader         string `long:"ip_header" env:"IP_HEADER" default:"X-Real-IP" description:"HTTP Request Header for remote IP"`
	UserHeader       string `long:"user_header" env:"USER_HEADER" default:"X-Username" description:"HTTP Request Header for username"`
	AccessLog        string `long:"access_log" env:"ACCESS_LOG" description:"HTTP access log filename (default: STDOUT, '-' means disable)"`
	UseETag          bool   `long:"etag" env:"ETAG" description:"Add ETAG in HTTP response"`
	ETagMaxBodyBytes int    `` /* 155-byte string literal not displayed */

	TLS     TLSConfig             `group:"HTTPS Options"            namespace:"tls"  env-namespace:"TLS"`
	Version VersionResponseConfig `group:"Version response Options" namespace:"vr"`
}

Config holds all config vars.

type Handler

type Handler func(http.Handler) http.Handler

Handler is a http midleware handler.

type Service

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

Service owns an HTTP server and its listener. Configure it before Run.

func New

func New(cfg Config) *Service

New returns *Service.

func (*Service) Run

func (srv *Service) Run(ctx context.Context) (err error)

Run serves HTTP(S) once. Context cancellation forces closure; use Shutdown to drain requests. The listener passed to WithListener is closed on return, including on error.

func (*Service) ServeMux

func (srv *Service) ServeMux() *http.ServeMux

ServeMux returns service muxer.

func (*Service) ServeMuxWithHandlers

func (srv *Service) ServeMuxWithHandlers() http.Handler

ServeMuxWithHandlers return mux joined with defined by Use handlers.

func (*Service) Shutdown

func (srv *Service) Shutdown(ctx context.Context) error

Shutdown stops admission and drains active requests within ctx. Before Run it closes a supplied listener and prevents serving. Later calls only wait for cleanup within their own context.

func (*Service) Use

func (srv *Service) Use(handler Handler) *Service

Use adds handler for muxer.

func (*Service) WithListener

func (srv *Service) WithListener(listener net.Listener) *Service

WithListener supplies a listener owned by the first Run or Shutdown call.

func (*Service) WithStatic

func (srv *Service) WithStatic(fSystem fs.FS) *Service

WithStatic sets static filesystem for serve via http.

func (*Service) WithVersion

func (srv *Service) WithVersion(version string) *Service

WithVersion sets hanler returning source code version as js.

type TLSConfig

type TLSConfig struct {
	CertFile           string `long:"cert" description:"CertFile for serving HTTPS instead HTTP" env:"CERT"`
	KeyFile            string `long:"key"  description:"KeyFile for serving HTTPS instead HTTP" env:"KEY"`
	NoCheckCertificate bool   `long:"no-check" description:"disable tls certificate validation"`
}

TLSConfig holds TLS config options.

type VersionResponseConfig

type VersionResponseConfig struct {
	Prefix string `long:"prefix" default:"/js/version.js" description:"URL for version response"`
	Format string `` /* 161-byte string literal not displayed */
	CType  string `long:"ctype"  default:"text/javascript" description:"js code Content-Type header"`
}

VersionResponseConfig holds settings for HTTP version response.

Jump to

Keyboard shortcuts

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