httpconfig

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MPL-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package httpconfig implements helpers around HTTP server configuration.

Package httpconfig is highly opiniated, double check that it fits you needs.

Index

Examples

Constants

View Source
const (
	// ConfigurationEnvVarPrefix is the prefix to use for configuration environment variables lookup.
	ConfigurationEnvVarPrefix = "Kema"
	// ApplicationConfigurationEnvVarPrefix is the prefix to use for application-specific configuration environment variables lookup.
	ApplicationConfigurationEnvVarPrefix = ConfigurationEnvVarPrefix + "Application"
	// EnvLocalValue is the value of [Runtime.Environment] that is used to denote a local development environment.
	EnvLocalValue = "dev"
)

Variables

View Source
var ErrCantMarshalConfig = errors.New("config is not marshallable to json")

ErrCantMarshalConfig reports an error in configuration marshalling.

Functions

func NewDBPostgresqlConfigOptionsFromHTTPConfig

func NewDBPostgresqlConfigOptionsFromHTTPConfig(conf DatabaseConfig) []dbpostgresql.Option

NewDBPostgresqlConfigOptionsFromHTTPConfig returns the options used to load dbpostgresql.Option values from Global.

func NewOtelSetupConfigOptionsFromHTTPConfig

func NewOtelSetupConfigOptionsFromHTTPConfig(
	runtimeConf Runtime,
	serverConf Server,
	logExportConf LogExport,
	metricExportConf MetricExport,
	traceExportConf TraceExport,
) []otelsetup.Option

NewOtelSetupConfigOptionsFromHTTPConfig returns the options used to load otelsetup.Option values from Global.

func NewServerConfigOptionsFromHTTPConfig

func NewServerConfigOptionsFromHTTPConfig(
	runtimeConf Runtime,
	serverConf Server,
) []server.Option

NewServerConfigOptionsFromHTTPConfig returns the options used to load server.Option values from Global.

Types

type Client

type Client struct {
	Database Database `required:"false"` // Database represents the database configuration.
	HTTP     HTTP     `required:"false"` // HTTP represents the HTTP configuration.
}

Client represents the clients configurations.

type Database

type Database struct {
	ReadWrite DatabaseConfig `required:"false"` // ReadWrite represents the database configuration for read/write operations.
	ReadOnly  DatabaseConfig `required:"false"` // ReadOnly represents the database configuration for read-only operations.
}

Database represents the database configurations.

type DatabaseConfig

type DatabaseConfig struct {
	User                              string            `required:"true"`  // User represents the user to use for the database.
	Host                              string            `required:"true"`  // Host represents the host to use for the database.
	Port                              int               `required:"true"`  // Port represents the port to use for the database.
	Database                          string            `required:"true"`  // Database represents the database to use for the database.
	ServerName                        string            `required:"true"`  // ServerName represents the servername to use for the database TLS certificate.
	CACertificatePath                 string            `required:"false"` // CACertificatePath represents the CA certificate file path to use for the database.
	PasswordFilePath                  string            `required:"false"` // PasswordFilePath represents the path to the file containing the password to use for the database.
	DBConnectionAdditionalQueryString map[string]string `required:"false"` // DBConnectionAdditionalQueryString represents additional parameters to use in the database connection string (DSN).
	MigrationTarget                   time.Time         `required:"false"` // MigrationTarget represents the database target version to run migrations to.
}

DatabaseConfig represents the database configuration.

type Global

type Global struct {
	Server        Server        `required:"false"` // Server represents the server configuration.
	Runtime       Runtime       `required:"false"` // Runtime represents the runtime configuration.
	Observability Observability `required:"false"` // Observability represents the observability configuration.
	Client        Client        `required:"false"` // Client represents the clients configurations.
}

Global represents the global configuration.

func Load

func Load[T any]() (*Global, *T, error)

Load returns server configuration Global and application-specific configuration [T], loaded from environment variables, according to struct tags.

Example
package main

import (
	"fmt"
	"log/slog"
	"os"

	"codeberg.org/kema/kmicro/pkg/http/httpconfig"
)

func main() {
	type config struct {
		Hello string `required:"true"`
		Def   string `default:"def"`
	}

	_ = os.Setenv(httpconfig.ConfigurationEnvVarPrefix+"RuntimeEnvironment", "Hello, World!")
	_ = os.Setenv(httpconfig.ApplicationConfigurationEnvVarPrefix+"Hello", "World!")

	glob, conf, err := httpconfig.Load[config]()
	if err != nil {
		slog.Error("loading configuration", slog.String("error.message", err.Error()))

		return
	}

	fmt.Printf("global:%q\n", glob.Runtime.Environment)
	fmt.Printf("hello:%q\n", conf.Hello)
	fmt.Printf("Def:%q\n", conf.Def)

}
Output:
global:"Hello, World!"
hello:"World!"
Def:"def"

type HTTP

type HTTP struct {
	ClusterCACertificatePath  string `required:"false"` // ClusterCACertificatePath represents the path to the file containing CA certificate to use for the cluster CA.
	InternetCACertificatePath string `required:"false"` // InternetCACertificatePath represents the path to the file containing CA certificate to use for the internet CA.
}

HTTP represents the HTTP configuration.

type LogExport

type LogExport struct {
	EndpointURL        url.URL `required:"true"`                 // EndpointURL represents the endpoint where to send telemetry.
	GzipCompression    bool    `required:"true"  default:"true"` // GzipCompression represents whether to use gzip compression when sending telemetry.
	TLSCAPath          string  `required:"false"`                // TLSCAPath represents the path to the file containing TLS CA certificate for the telemetry endpoint.
	TLSCertificatePath string  `required:"false"`                // TLSCertificatePath represents the path to the file containing TLS certificate for the telemetry endpoint.
	TLSKeyPath         string  `required:"false"`                // TLSKeyPath represents the path to the file containing TLS key for the telemetry endpoint.
}

LogExport represents the log export configuration.

type MetricExport

type MetricExport struct {
	EndpointURL        url.URL       `required:"true"`                 // EndpointURL represents the endpoint where to send telemetry.
	GzipCompression    bool          `required:"true"  default:"true"` // GzipCompression represents whether to use gzip compression when sending telemetry.
	ExportInterval     time.Duration `required:"true"  default:"15s"`  // ExportInterval represents the interval between metrics exports.
	TLSCAPath          string        `required:"false"`                // TLSCAPath represents the path to the file containing TLS CA certificate for the telemetry endpoint.
	TLSCertificatePath string        `required:"false"`                // TLSCertificatePath represents the path to the file containing TLS certificate for the telemetry endpoint.
	TLSKeyPath         string        `required:"false"`                // TLSKeyPath represents the path to the file containing TLS key for the telemetry endpoint.
}

MetricExport represents the metric export configuration.

type Observability

type Observability struct {
	Log    LogExport    `required:"false"` // Log represents the log export configuration.
	Metric MetricExport `required:"false"` // Metric represents the metric export configuration.
	Trace  TraceExport  `required:"false"` // Trace represents the trace export configuration.
}

Observability represents the observability configuration.

type Runtime

type Runtime struct {
	Environment           string         `required:"false"` // Environment represents the environment the service runs in.
	AppVersion            semver.Version `required:"false"` // AppVersion represents the service version.
	AppName               string         `required:"false"` // AppName represents the service name.
	AppInstance           string         `required:"false"` // AppInstance represents the service instance.
	AppNamespace          string         `required:"false"` // AppNamespace represents the service namespace.
	CloudRegion           string         `required:"false"` // CloudRegion represents the region the application runs in.
	CloudAvailabilityZone string         `required:"false"` // CloudAvailabilityZone represents the availability zone the application runs in.
	K8sNodeName           string         `required:"false"` // NodeName represents the kubernetes node name the application runs in.
}

Runtime represents the runtime configuration.

func (*Runtime) IsLocalEnvironment

func (conf *Runtime) IsLocalEnvironment() bool

IsLocalEnvironment returns whether the application in running in a local development environment from conf.Environment.

func (*Runtime) SlogLevel

func (conf *Runtime) SlogLevel() slog.Level

SlogLevel returns the appropriate slog.Level for conf.Runtime.

type Server

type Server struct {
	BindAddr             string        `default:"::"        required:"true"`  // BindAddr represents the bind address for the HTTP server.
	BindPort             int           `default:"8080"      required:"true"`  // BindPort represents the bind port for the HTTP server.
	HealthBindAddr       string        `default:"::"        required:"true"`  // HealthBindAddr represents the bind address for the health HTTP server.
	HealthBindPort       int           `default:"8081"      required:"true"`  // HealthBindPort represents the bind port for the health HTTP server.
	ReadHeaderTimeout    time.Duration `default:"5s"        required:"true"`  // ReadTimeout represents the HTTP read header timeout for the HTTP server.
	ReadTimeout          time.Duration `                    required:"false"` // ReadTimeout represents the HTTP read timeout for the HTTP server.
	WriteTimeout         time.Duration `                    required:"false"` // WriteTimeout represents the HTTP write timeout for the HTTP server.
	IdleTimeout          time.Duration `default:"60s"       required:"true"`  // IdleTimeout represents the HTTP idle timeout for the HTTP server.
	ShutdownGracePeriod  time.Duration `default:"5s"        required:"true"`  // ShutdownGracePeriod represents the grace period to give the server before canceling contexts upon shutdown.
	ShutdownFuncsTimeout time.Duration `default:"5s"        required:"true"`  // ShutdownFuncsTimeout represents the time to give the shutdown functions before canceling contexts upon shutdown.
	TLSCertificatePath   string        `                    required:"false"` // TLSCertificatePath represents the path to the file containing TLS certificate for the server.
	TLSKeyPath           string        `                    required:"false"` // TLSKeyPath represents the path to the file containing TLS key for the server.
}

Server represents the server configuration.

type TraceExport

type TraceExport struct {
	EndpointURL        url.URL       `required:"true"`                 // EndpointURL represents the endpoint where to send telemetry.
	GzipCompression    bool          `required:"true"  default:"true"` // GzipCompression represents whether to use gzip compression when sending telemetry.
	SampleRatio        float64       `required:"true"  default:"1"`    // SamplePercent represents the ratio of request to sample for tracing.
	BatchTimeout       time.Duration `required:"false"`                // BatchTimeout represents the batch timeout to use for traces.
	TLSCAPath          string        `required:"false"`                // TLSCAPath represents the path to the file containing TLS CA certificate for the telemetry endpoint.
	TLSCertificatePath string        `required:"false"`                // TLSCertificatePath represents the path to the file containing TLS certificate for the telemetry endpoint.
	TLSKeyPath         string        `required:"false"`                // TLSKeyPath represents the path to the file containing TLS key for the telemetry endpoint.
}

TraceExport represents the trace export configuration.

Jump to

Keyboard shortcuts

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