http

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 8 Imported by: 2

README

Package http

Пакет http предоставляет инструменты для создания и управления HTTP-сервером с поддержкой middleware, обработки запросов и гибкой настройки. Интегрируется с системой логирования и обработки ошибок.

Types

Server

Структура Server управляет жизненным циклом HTTP-сервера, включая запуск, остановку и динамическое обновление обработчиков.

Methods:

NewServer(logger log.Logger, opts ...ServerOption) *Server

Конструктор сервера. Дополнительно принимает опции:

  • WithServer(server *http.Server) ServerOption – использование объекта предварительно настроенного HTTP-сервера из стандартной библиотеки net/http.
(s *Server) Upgrade(handler http.Handler)

Атомарно заменить текущий обработчик запросов на новый.

(s *Server) ListenAndServe(address string) error

Запустить сервер на указанном адресе.

(s *Server) Serve(listener net.Listener) error

Запустить сервер на существующем listener.

(s *Server) Shutdown(ctx context.Context) error

Остановить сервер, завершив все активные соединения.

Usage

Default usage flow
package main

import (
	"context"
	"log"
	"net/http"

	http2 "github.com/txix-open/isp-kit/http"
	log2 "github.com/txix-open/isp-kit/log"
	"github.com/txix-open/isp-kit/shutdown"
)

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}

	srv := http2.NewServer(logger)
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("hello world!!"))
	})

	srv.Upgrade(mux)

	shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
		log.Println("shutting down...")
		_ = srv.Shutdown(context.Background())
		log.Println("shutdown completed")
	})

	err = srv.ListenAndServe(":8080")
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package http provides core HTTP server functionality and types for building REST and SOAP services. It includes a server implementation, handler wrapper, and middleware support for request processing.

nolint:mnd

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc

type HandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error

HandlerFunc is the signature for HTTP handlers that process requests in a context-aware manner. Handlers should return an error to indicate processing failure.

type Middleware

type Middleware func(next HandlerFunc) HandlerFunc

Middleware is a function that wraps a HandlerFunc to add cross-cutting concerns such as logging, authentication, or metrics collection.

type Server

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

Server wraps an http.Server with additional functionality for handler management. It provides graceful shutdown and handler upgrade capabilities.

func NewServer

func NewServer(logger log.Logger, opts ...ServerOption) *Server

NewServer creates a new HTTP server with the specified logger and options. Default timeouts are set: 3 seconds for ReadHeaderTimeout and 120 seconds for IdleTimeout. Server is safe for concurrent use.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(address string) error

ListenAndServe starts the server on the specified address. It creates a TCP listener and delegates to Serve.

func (*Server) Serve

func (s *Server) Serve(listener net.Listener) error

Serve accepts incoming connections on the specified listener and handles requests. It returns nil when the server is gracefully shut down.

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server without interrupting any active connections. It delegates to the underlying http.Server.Shutdown method.

func (*Server) Upgrade

func (s *Server) Upgrade(handler http.Handler)

Upgrade replaces the current HTTP handler with a new one. This method is safe for concurrent use.

type ServerOption

type ServerOption func(*Server)

ServerOption is a function that configures a Server instance.

func WithServer

func WithServer(server *http.Server) ServerOption

WithServer allows providing a custom *http.Server for advanced configuration.

Directories

Path Synopsis
Package apierrors provides HTTP error handling with structured error responses.
Package apierrors provides HTTP error handling with structured error responses.
bench module
Package endpoint provides a high-level abstraction for building HTTP endpoints with automatic request/response handling, validation, and middleware support.
Package endpoint provides a high-level abstraction for building HTTP endpoints with automatic request/response handling, validation, and middleware support.
buffer
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
httplog
Package httplog provides HTTP request/response logging middleware.
Package httplog provides HTTP request/response logging middleware.
Package httpcli provides a high-level HTTP client with support for middleware, retries, and flexible request/response handling.
Package httpcli provides a high-level HTTP client with support for middleware, retries, and flexible request/response handling.
Package httpclix provides extended HTTP client functionality including load balancing, logging, and observability middleware.
Package httpclix provides extended HTTP client functionality including load balancing, logging, and observability middleware.
Package router provides HTTP request routing with metrics integration.
Package router provides HTTP request routing with metrics integration.
Package soap provides SOAP message handling for XML-based web services.
Package soap provides SOAP message handling for XML-based web services.
client
Package client provides a SOAP client for invoking SOAP web services.
Package client provides a SOAP client for invoking SOAP web services.

Jump to

Keyboard shortcuts

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