http

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Header contains predefined headers.
	Header = struct {
		AcceptLanguage  string
		Authorization   string
		ContentLanguage string
		ContentType     string
		WWWAuthenticate string
		XRequestID      string
		AmazonTraceID   string
	}{
		AcceptLanguage:  "Accept-Language",
		Authorization:   "Authorization",
		ContentLanguage: "Content-Language",
		ContentType:     "Content-Type",
		WWWAuthenticate: "WWW-Authenticate",
		XRequestID:      "X-Request-Id",
		AmazonTraceID:   "X-Amzn-Trace-Id",
	}
)

Functions

func DecodeJSON

func DecodeJSON(data any, v any) error

DecodeJSON decodes data using JSON marshaling into the type of parameter v.

func EncodeJSON

func EncodeJSON(w http.ResponseWriter, data any) error

func LoggingMiddleware

func LoggingMiddleware(l *slog.Logger) func(http.Handler) http.Handler

LoggingMiddleware logs:

  • URL path
  • HTTP method
  • Request ID
  • Duration of a request
  • HTTP status code
  • Error object if exists
  • Panic object if exists

If the status code >= http.StatusInternalServerError, logs with error level, info otherwise.

func MustDecodeJSON

func MustDecodeJSON(data any, v any)

MustDecodeJSON calls DecodeJSON and panics on error.

func RecoverMiddleware

func RecoverMiddleware(l *slog.Logger, opts ...RecoverMiddlewareOption) func(http.Handler) http.Handler

RecoverMiddleware calls next handler and recovers from a panic. If a panic occurs, log this event, set http.StatusInternalServerError as a status code and save a panic object into the response writer.

func RequestIDMiddleware

func RequestIDMiddleware(f RequestIDFunc) func(http.Handler) http.Handler

RequestIDMiddleware saves request ID into the request context. If context already contains request ID, next handler is called. If the user provided function returns empty request ID, a new one is generated.

func WriteErrorResponse

func WriteErrorResponse(
	w http.ResponseWriter,
	statusCode int,
	opts ...ErrorResponseOption,
) error

func WriteResponse

func WriteResponse(
	w http.ResponseWriter,
	data any,
	statusCode int,
	opts ...ResponseOption,
) error

Types

type CharsetType

type CharsetType string
const UTF8 CharsetType = "utf-8"

type ContentType

type ContentType string

ContentType contains predefined mime types.

const (
	ApplicationJSON  ContentType = "application/json"
	ApplicationXML   ContentType = "application/xml"
	ApplicationXYAML ContentType = "application/x-yaml"
	ApplicationYAML  ContentType = "application/yaml"

	TextJSON  ContentType = "text/json"
	TextXML   ContentType = "text/xml"
	TextXYAML ContentType = "text/x-yaml"
	TextYAML  ContentType = "text/yaml"

	ImageGIF  ContentType = "image/gif"
	ImageJPEG ContentType = "image/jpeg"
	ImagePNG  ContentType = "image/png"
	ImageSVG  ContentType = "image/svg+xml"
	ImageWebP ContentType = "image/webp"
)

func (ContentType) WithCharset

type ContentTypeWithCharset

type ContentTypeWithCharset struct {
	ContentType ContentType
	CharsetType CharsetType
}

func (ContentTypeWithCharset) String

func (c ContentTypeWithCharset) String() string

type EncodeFunc

type EncodeFunc func(w http.ResponseWriter, data any) error

EncodeFunc is a function that encodes data to the response writer.

type ErrorResponseOption

type ErrorResponseOption func(*ErrorResponseOptions)

func WithError added in v0.3.0

func WithError(err error) ErrorResponseOption

func WithErrorCode

func WithErrorCode(code string) ErrorResponseOption

func WithErrorData

func WithErrorData(data any) ErrorResponseOption

func WithErrorMessage added in v0.5.0

func WithErrorMessage(msg string) ErrorResponseOption

func WithRequestID added in v0.5.0

func WithRequestID(id string) ErrorResponseOption

type ErrorResponseOptions

type ErrorResponseOptions struct {
	ResponseOptions `json:"-"`

	RequestID string `json:"requestId,omitempty"`

	Err        error  `json:"-"`
	ErrCode    string `json:"errorCode"`
	ErrMessage string `json:"errorMessage,omitempty"`
	ErrData    any    `json:"errorData,omitempty"`
}

type Limits

type Limits struct {
	// Timeouts is a configuration of specific timeouts.
	Timeouts *Timeouts `json:"timeouts,omitempty"`

	// MaxHeaderBytes is part of http.Server.
	// See http.Server for more details.
	MaxHeaderBytes int `json:"max_header_bytes"`
}

Limits define timeouts and header restrictions.

type RecoverMiddlewareOption added in v0.7.0

type RecoverMiddlewareOption func(*RecoverMiddlewareOptions)

func WithStackTrace added in v0.7.0

func WithStackTrace() RecoverMiddlewareOption

type RecoverMiddlewareOptions added in v0.7.0

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

type RequestData added in v0.7.0

type RequestData struct {
	Path               string
	Method             string
	Duration           time.Duration
	ResponseStatusCode int
	RequestID          string
}

RequestData contains processed request data for logging purposes. Path is path from URL of the request. Method is HTTP request method. Duration is how long it took to process whole request. ResponseStatusCode is HTTP status code which was returned. RequestID is unique identifier of request. Err is error object containing error message. Panic is panic object containing error message.

func (RequestData) LogValue added in v0.7.0

func (r RequestData) LogValue() slog.Value

type RequestIDFunc

type RequestIDFunc func(h http.Header) string

RequestIDFunc is used for obtaining a request ID from the HTTP header.

type ResponseOption

type ResponseOption func(*ResponseOptions)

func WithCharsetType

func WithCharsetType(c CharsetType) ResponseOption

func WithContentType

func WithContentType(c ContentType) ResponseOption

func WithEncodeFunc

func WithEncodeFunc(fn EncodeFunc) ResponseOption

type ResponseOptions

type ResponseOptions struct {
	EncodeFunc  EncodeFunc
	ContentType ContentType
	CharsetType CharsetType
}

type Server

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

func NewServer

func NewServer(config *ServerConfig) *Server

func (*Server) Run

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

Run calls ListenAndServe but returns error only if err != http.ErrServerClosed. Passed context is used as base context of all http requests and to shutdown server gracefully.

type ServerConfig

type ServerConfig struct {
	// Addr is address where HTTP server is listening.
	Addr string `json:"addr"`

	// Handler handles HTTP requests.
	Handler http.Handler `json:"-"`

	// Hooks are server hooks.
	Hooks ServerHooks `json:"-"`

	// Limits are server limits, like timeouts and header restrictions.
	Limits *Limits `json:"limits,omitempty"`

	// Logger is server logger.
	Logger *slog.Logger
}

ServerConfig represents Server configuration.

type ServerHookFunc

type ServerHookFunc func(context.Context)

type ServerHooks

type ServerHooks struct {
	BeforeShutdown []ServerHookFunc
}

type Timeouts

type Timeouts struct {
	// ShutdownTimeout is a timeout before server shutdown.
	//
	// If not provided, the default value is used (30 seconds), if the timeout is less or equal to 0, the server is shutdown immediately,
	// otherwise the server is shutdown after the timeout.
	ShutdownTimeout *time.Duration `json:"shutdown_timeout"`

	// IdleTimeout is part of http.Server.
	// See http.Server for more details.
	IdleTimeout time.Duration `json:"idle_timeout"`

	// ReadTimeout is part of http.Server.
	// See http.Server for more details.
	ReadTimeout time.Duration `json:"read_timeout"`

	// WriteTimeout is part of http.Server.
	// See http.Server for more details.
	WriteTimeout time.Duration `json:"write_timeout"`

	// ReadHeaderTimeout is part of http.Server.
	// See http.Server for more details.
	ReadHeaderTimeout time.Duration `json:"read_header_timeout"`
}

Timeouts represents configuration for HTTP server timeouts.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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