httpserver

package
v6.0.2 Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package httpserver provides configuration options for an HTTP server.

Package httpserver provides utilities for managing an HTTP server, including logging and response handling.

Package httpserver contains basic HTTPServer based on gin.Engine

Example
package main

import (
	"github.com/sabariramc/goserverbase/v6/app/server/httpserver"
)

func main() {
	srv := httpserver.New()
	srv.StartServer()
}
Output:

Example (Routes)
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/sabariramc/goserverbase/v6/app/server/httpserver"
)

func main() {
	srv := httpserver.New()
	r := srv.GetRouter()
	r.Group("/test").GET("", func(ctx *gin.Context) {
		l := srv.GetLogger()
		l.Info(ctx, "test route")
	})
	srv.StartServer()
}
Output:

Index

Examples

Constants

View Source
const (
	HttpContentTypeJSON   = "application/json"
	HttpHeaderContentType = "Content-Type"
)

Variables

This section is empty.

Functions

func MethodNotAllowed

func MethodNotAllowed() http.HandlerFunc

MethodNotAllowed returns a handler function for responding with a 405 Method Not Allowed status.

func NotFound

func NotFound() http.HandlerFunc

NotFound returns a handler function for responding with a 404 Not Found status.

Types

type Config

type Config struct {
	*baseapp.Config
	*DocumentationConfig
	*TLSConfig
	Host   string      // Host address
	Port   string      // Port number
	Log    log.Log     // Logger instance
	Mask   *MaskConfig // Configuration for masking headers
	Tracer Tracer      // Tracer instance
}

Config holds the configuration for the HTTP server.

func GetDefaultConfig

func GetDefaultConfig() *Config

GetDefaultConfig returns the default HTTPServerConfig with values from environment variables or default values.

Environment Variables
- HTTP_SERVER__HOST: Sets [Host]
- HTTP_SERVER__PORT: Sets [Port]

type DocumentationConfig

type DocumentationConfig struct {
	DocHost    string // Host for the documentation server
	RootFolder string // Local disk folder for the OpenAPI documentation server
}

DocumentationConfig holds the configuration for serving documentation.

func GetDocumentationConfig

func GetDocumentationConfig() *DocumentationConfig

GetDocumentationConfig returns the default DocumentationConfig with values from environment variables or default values.

Environment Variables
- HTTP_SERVER__DOC_HOST: Sets [DocHost]
- HTTP_SERVER__DOC_ROOT_FOLDER: Sets [RootFolder]

type HTTPServer

type HTTPServer struct {
	*baseapp.BaseApp
	// contains filtered or unexported fields
}

HTTPServer represents an HTTP server, extends gin.Engine with additional middleware and OpenAPI documentation Implements ShutdownHook, HealthCheckHook and StatusCheckHook

func New

func New(options ...Option) *HTTPServer

New creates a new instance of HTTPServer.

func (*HTTPServer) AddMiddleware

func (h *HTTPServer) AddMiddleware(middleware ...gin.HandlerFunc)

AddMiddleware adds custom middleware to the HTTPServer.

func (*HTTPServer) BootstrapServer

func (h *HTTPServer) BootstrapServer(ctx context.Context, handler http.Handler) error

BootstrapServer initializes the HTTP server with the given handler and starts monitoring for shutdown signals.

func (*HTTPServer) CopyRequestBody

func (h *HTTPServer) CopyRequestBody(r *http.Request) ([]byte, error)

CopyRequestBody copies the request body and returns it as a byte slice.

func (*HTTPServer) ExtractRequestMetadata

func (h *HTTPServer) ExtractRequestMetadata(r *http.Request) map[string]any

ExtractRequestMetadata extracts metadata from the HTTP request.

func (*HTTPServer) GetCorrelationParams

func (h *HTTPServer) GetCorrelationParams(r *http.Request) *correlation.CorrelationParam

GetCorrelationParams extracts correlation parameters from the request headers. If the correlation ID is missing, it generates a new one using the service name.

func (*HTTPServer) GetCustomerID

func (h *HTTPServer) GetCustomerID(r *http.Request) *correlation.UserIdentifier

GetCustomerID extracts user identifiers from the request headers.

func (*HTTPServer) GetMaskedRequestMeta

func (h *HTTPServer) GetMaskedRequestMeta(r *http.Request) map[string]any

GetMaskedRequestMeta extracts request metadata and masks sensitive headers specified in the configuration.

func (*HTTPServer) GetPort

func (h *HTTPServer) GetPort() string

GetPort returns the host and port of the HTTP server.

func (*HTTPServer) GetRequestBody

func (h *HTTPServer) GetRequestBody(r *http.Request) ([]byte, error)

GetRequestBody reads and returns the request body as a byte slice.

func (*HTTPServer) GetRouter

func (h *HTTPServer) GetRouter() *gin.Engine

GetRouter returns the underlying gin.Engine instance.

func (*HTTPServer) GetSpanFromContext

func (h *HTTPServer) GetSpanFromContext(ctx context.Context) (span.Span, bool)

GetSpanFromContext retrieves the telemetry span from the given context, if the server is initiated with a tracer

func (*HTTPServer) HealthCheck

func (h *HTTPServer) HealthCheck(w http.ResponseWriter, r *http.Request)

HealthCheck handles the HTTP request for the health check endpoint. It runs the health check and returns a 500 status code if there is an error, otherwise it returns a 204 status code.

func (*HTTPServer) LoadRequestJSONBody

func (h *HTTPServer) LoadRequestJSONBody(r *http.Request, body any) error

LoadRequestJSONBody reads the request body and unmarshals it into the provided interface.

func (*HTTPServer) LogRequestResponseMiddleware

func (h *HTTPServer) LogRequestResponseMiddleware() gin.HandlerFunc

LogRequestResponseMiddleware returns a middleware that logs the request and response.

func (*HTTPServer) Name

func (h *HTTPServer) Name(ctx context.Context) string

Name returns the name of the HTTPServer. Implementation of the hook interface defined in the BaseApp

func (*HTTPServer) PanicHandleMiddleware

func (h *HTTPServer) PanicHandleMiddleware() gin.HandlerFunc

PanicHandleMiddleware returns a middleware that recovers from panics and logs the error and stack trace.

func (*HTTPServer) RequestTimerMiddleware

func (h *HTTPServer) RequestTimerMiddleware() gin.HandlerFunc

RequestTimerMiddleware returns a middleware that logs the request processing time.

func (*HTTPServer) ServeHTTP

func (h *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*HTTPServer) SetCorrelationMiddleware

func (h *HTTPServer) SetCorrelationMiddleware() gin.HandlerFunc

SetCorrelationMiddleware returns a middleware that sets the correlation parameters and user identifier in the request context.

func (*HTTPServer) SetupDocumentation

func (h *HTTPServer) SetupDocumentation(ctx context.Context)

SetupDocumentation configures routes for serving OpenAPI documentation. By default documentation is served in <<host>>/meta/docs/index.html The local root folder for the documentation can be configured with config.SwaggerRootFolder, the root folder should contain swagger.yaml

func (*HTTPServer) SetupRouter

func (h *HTTPServer) SetupRouter(ctx context.Context)

SetupRouter configures routes and middleware for the HTTPServer.

func (*HTTPServer) Shutdown

func (h *HTTPServer) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server. Implementation for shutdown hook

func (*HTTPServer) StartH2CServer

func (h *HTTPServer) StartH2CServer()

StartH2CServer starts the HTTP/2 server in cleartext mode (h2c) and listens for incoming requests. It logs the startup and handles any server errors.

func (*HTTPServer) StartServer

func (h *HTTPServer) StartServer()

StartServer starts the HTTP server and listens for incoming requests. It logs the startup and handles any server errors.

func (*HTTPServer) StartTLSServer

func (h *HTTPServer) StartTLSServer()

StartTLSServer starts the HTTPS server using TLS and listens for incoming requests. It logs the startup and handles any server errors.

func (*HTTPServer) Status

func (h *HTTPServer) Status(w http.ResponseWriter, r *http.Request)

Status handles the HTTP request for the status endpoint. It runs the status check and writes the JSON response.

func (*HTTPServer) StatusCheck

func (h *HTTPServer) StatusCheck(ctx context.Context) (any, error)

StatusCheck performs the status check of the server and returns a map containing the current connection count.

func (*HTTPServer) WriteErrorResponse

func (h *HTTPServer) WriteErrorResponse(ctx context.Context, w http.ResponseWriter, err error, stackTrace string)

WriteErrorResponse writes an error response, logging the error and stack trace.

func (*HTTPServer) WriteJSON

func (h *HTTPServer) WriteJSON(ctx context.Context, w http.ResponseWriter, responseBody any)

WriteJSON writes a JSON response with a status code of 200 OK.

func (*HTTPServer) WriteJSONWithStatusCode

func (h *HTTPServer) WriteJSONWithStatusCode(ctx context.Context, w http.ResponseWriter, statusCode int, responseBody any)

WriteJSONWithStatusCode writes a JSON response with the specified status code.

func (*HTTPServer) WriteResponse

func (h *HTTPServer) WriteResponse(ctx context.Context, w http.ResponseWriter, contentType string, responseBody []byte)

WriteResponse writes a response with a status code of 200 OK and the specified content type.

func (*HTTPServer) WriteResponseWithStatusCode

func (h *HTTPServer) WriteResponseWithStatusCode(ctx context.Context, w http.ResponseWriter, statusCode int, contentType string, responseBody []byte)

WriteResponseWithStatusCode writes a response with the specified status code and content type.

type MaskConfig

type MaskConfig struct {
	HeaderKeyList []string // List of header keys to mask before logging request
}

MaskConfig holds the configuration for masking headers in log messages.

func GetDefaultMaskConfig

func GetDefaultMaskConfig() *MaskConfig

GetDefaultMaskConfig returns the default MaskConfig with values from environment variables or default values.

Environment Variables
- HTTP_SERVER__MASK__HEADER_KEY_LIST: Sets [HeaderKeyList]

type Option

type Option func(*Config)

Option represents a function that applies a configuration option to HTTPServerConfig.

func WithBaseAppConfig

func WithBaseAppConfig(baseCfg *baseapp.Config) Option

WithBaseAppConfig sets the baseapp.Config embedded field of HTTPServerConfig.

func WithDocumentationConfig

func WithDocumentationConfig(docCfg *DocumentationConfig) Option

WithDocumentationConfig sets the DocumentationConfig embedded field of HTTPServerConfig.

func WithHTTP2Config

func WithHTTP2Config(http2Cfg *TLSConfig) Option

WithHTTP2Config sets the TLSConfig embedded field of HTTPServerConfig.

func WithHost

func WithHost(host string) Option

WithHost sets the Host field of HTTPServerConfig.

func WithLog

func WithLog(log log.Log) Option

WithLog sets the Log field of HTTPServerConfig.

func WithMask

func WithMask(m MaskConfig) Option

WithMask sets the Log field of HTTPServerConfig.

func WithPort

func WithPort(port string) Option

WithPort sets the Port field of HTTPServerConfig.

func WithTracer

func WithTracer(t Tracer) Option

WithTracer sets the Tracer field of HTTPServerConfig.

type TLSConfig

type TLSConfig struct {
	PublicKeyPath  string // Local disk path for the public key
	PrivateKeyPath string // Local disk path for the private key
}

TLSConfig holds the configuration for HTTPS.

func GetDefaultTLSConfig

func GetDefaultTLSConfig() *TLSConfig

GetDefaultTLSConfig returns the default TLSConfig with values from environment variables or default values.

Environment Variables
- HTTP_SERVER__TLS_PUBLIC_KEY: Sets [PublicKeyPath]
- HTTP_SERVER__TLS_PRIVATE_KEY: Sets [PrivateKeyPath]

type Tracer

type Tracer interface {
	GetGinMiddleware(serviceName string) gin.HandlerFunc
	span.SpanOp
}

Tracer defines the interface for tracing functionality.

Directories

Path Synopsis
h2c

Jump to

Keyboard shortcuts

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