odj

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: BSD-3-Clause Imports: 48 Imported by: 0

README

go-odj

go-odj is a package that holds a number of utilities that are used frequently in ODJ Go-based applications.

Utilities

  • Bootstrap: a pre-defined bootstrap function that:
    1. Sets timezone to UTC
    2. Adds a lifecycle into context for closers to register with
    3. Sets up a logger into context
    4. Sets up maxprocs
  • Logging: returns a logger in context based on deployment stage
  • OpenAPISpecHandler: provides a handler for the rendered OpenAPI spec from bytes of a HTML file
  • Info: provides a handler that can be used for /info, /readiness and /liveness routes. It contains basic information about the service such as version, build time and git commit. Note that the version, build time and git commit are expected to be set at build time using ldflags.
  • Stage: provides ODJ stages using an enum and env loading.
  • OgenError: provides an error handlers compatible with tagerr Errors.
  • Otel: provides an OTEL trace provider
  • OtelProxy: provides a handler that can be used to proxy Otel spans to a configured Otel collector.
  • Postgres: provides Postgres with Tracing and Ready-to-use test containers.
  • SIAM: provides a helper that can read SIAM group membership claim regardless of it being a string or an array.
  • Env: provides a helper to reload environment variables, in case of a late environment variable loading.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BuildDate string

BuildDate is the build date of the binary, which is expected to be set at build time using ldflags. Defaults to an empty string if not set. e.g. -ldflags="-X github.com/pedramktb/go-odj.BuildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"

View Source
var Component string

Component is the component name of the ODJ component, determined by the ODJ_EE_COMPONENT environment variable. It defaults to "unknown" if not set or empty.

View Source
var FullVersion string

FullVersion is the full semver string of the binary, which is constructed based on the Version, Iter, and Stage variables. It follows the format "version[-preRelease.iter]" where preRelease is determined by the Stage: - For StageProd and StageTest, there is no preRelease suffix. - For StageQA, the preRelease suffix is "-rc". - For StageDev, the preRelease suffix is "-beta". - For any other stage (including StageLocal), the preRelease suffix is "-alpha" if the version is not "dev". If Iter is empty, it will be omitted from the version string.

View Source
var GitSHA string

GitSHA is the Git commit SHA of the binary, which is expected to be set at build time using ldflags. Defaults to an empty string if not set. e.g. -ldflags="-X github.com/pedramktb/go-odj.GitSHA=$(git rev-parse HEAD)"

View Source
var Iter string

Iter is the build number in the Azure DevOps pipeline, which is expected to be set at build time using ldflags. Defaults to an empty string if not set. e.g. -ldflags="-X github.com/pedramktb/go-odj.Iter=$(Build.BuildNumber)"

View Source
var Product string

Product is the product name of the ODJ component, determined by the ODJ_EE_PRODUCT environment variable. It defaults to "unknown" if not set or empty.

View Source
var SIAMMembershipStage string

SIAMMembershipStage is the stage value used for SIAM membership, which maps "prod" to "prod" and all other stages to "test".

View Source
var Version string

Version is the version core part (vM.m.p) of the semver of the binary, which is expected to be set at build time using ldflags. Defaults to "dev" if not set. e.g. -ldflags="-X github.com/pedramktb/go-odj.Version=1.2.3"

Functions

func Bootstrap

func Bootstrap() (context.Context, context.CancelFunc, <-chan error)

Bootstrap initializes the application context with logging, and lifecycle management. It sets the timezone to UTC and configures the maximum number of CPU cores to use based on the container's limits.

The function returns a context that should be used throughout the application, a cancel function to trigger shutdown, and a channel that will receive any errors that occur during shutdown.

func InfoHandler

func InfoHandler(deps ...func(ctx context.Context) (depName string, jsonBytes []byte)) func(w http.ResponseWriter, r *http.Request)

InfoHandler returns an HTTP handler function that serves build and version information as a JSON response.

func Logging

func Logging(ctx context.Context) context.Context

Logging returns a new context with an attached slog logger. Whenever logging with this logger, if the context at that time contains an active OpenTelemetry span, the logger will automatically include the trace_id and span_id as attributes in the log records.

func NewOtelTraceProxy

func NewOtelTraceProxy(srcComponent, endpoint, user, pass string) (http.Handler, error)

NewOtelTraceProxy creates a new OpenTelemetry proxy handler that forwards OTLP/HTTP protobuf requests to a configured OTel gRPC collector. This is because ODJ/StackIT did not feel like implementing/allowing OTLP/HTTP.

func OgenEndpointNotFoundErrorHandler

func OgenEndpointNotFoundErrorHandler(w http.ResponseWriter, r *http.Request)

OgenEndpointNotFoundErrorHandler is a custom error handler for handling "endpoint not found" errors in the Ogen framework.

func OgenErrorHandler

func OgenErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)

OgenErrorHandler is a custom error handler for the Ogen framework that processes different types of errors and generates appropriate HTTP responses. It checks the error type and maps it to a corresponding tagged error, which is then logged and returned as a JSON response with the appropriate HTTP status code and error details. Errors of type tagerr.Err are returned as-is.

func OgenMethodNotAllowedErrorHandler

func OgenMethodNotAllowedErrorHandler(w http.ResponseWriter, r *http.Request, allowed string)

OgenMethodNotAllowedErrorHandler is a custom error handler for handling "method not allowed" errors in the Ogen framework.

func OpenAPISpecHandler

func OpenAPISpecHandler(spec []byte) http.HandlerFunc

OpenAPISpecHandler returns an HTTP handler function that serves the provided OpenAPI specification as a response to incoming requests. The handler sets the response status to 200 OK and the Content-Type header to "text/html; charset=utf-8" before writing the OpenAPI specification bytes to the response body.

func OtelTrace

func OtelTrace(ctx context.Context, exporter sdktrace.SpanExporter) (context.Context, error)

OtelTrace initializes an OpenTelemetry tracer provider with the given SpanExporter.

func OtelTraceGCPExporter added in v1.1.4

func OtelTraceGCPExporter(projectID string) (sdktrace.SpanExporter, error)

OtelTraceGCPExporter creates a Google Cloud Trace SpanExporter using Application Default Credentials. projectID may be empty to auto-detect from the GCP metadata server.

func OtelTraceGRPCBasicAuthExporter added in v1.1.4

func OtelTraceGRPCBasicAuthExporter(ctx context.Context, endpoint, user, pass string) (sdktrace.SpanExporter, error)

OtelTraceGRPCBasicAuthExporter creates an OTLP gRPC SpanExporter using basic authentication.

func OtelTraceMiddleware

func OtelTraceMiddleware(next http.Handler) http.Handler

OtelTraceMiddleware is an HTTP middleware that extracts OpenTelemetry trace context from incoming requests and injects it into the request context.

func Postgres

func Postgres(ctx context.Context, endpoint, db, user, pass string, opts ...typx.KV[string, string]) (*pgxpool.Pool, error)

Postgres establishes a connection pool to a PostgreSQL database using the provided connection parameters and options.

func PostgresTestContainer

func PostgresTestContainer(ctx context.Context, opts ...typx.KV[string, string]) (container testcontainers.Container)

PostgresTestContainer starts a new Postgres test container with the specified options and returns the container instance. It sets the timezone to UTC and waits for the database system to be ready before returning.

func PostgresTestContainerCreateDB

func PostgresTestContainerCreateDB(ctx context.Context, container testcontainers.Container, name string, opts ...typx.KV[string, string]) *pgxpool.Pool

PostgresTestContainerCreateDB creates a new database with the specified name in the given Postgres test container, using the provided connection options. It first establishes a connection to the "postgres" database, executes the CREATE DATABASE command, and then returns a new connection pool to the newly created database.

func PostgresTestContainerDropDB

func PostgresTestContainerDropDB(ctx context.Context, container testcontainers.Container, name string, pool *pgxpool.Pool, opts ...typx.KV[string, string])

PostgresTestContainerDropDB drops the specified database from the given Postgres test container, using the provided connection pool to execute the drop command. It first closes the existing pool, creates a new connection to the "postgres" database, executes the drop command with force option, and then closes the pool again.

func PostgresTestContainerSetupDB

func PostgresTestContainerSetupDB(ctx context.Context, t *testing.T, container testcontainers.Container, opts ...typx.KV[string, string]) *pgxpool.Pool

PostgresTestContainerSetupDB creates a new database in the given Postgres test container with a name derived from the test name, and returns a connection pool to that database. It also registers a cleanup function to drop the database after the test completes.

func ReloadEnv

func ReloadEnv()

ReloadEnv reloads the environment by reloading all environment variables and derived values. It updates:

  • Stage
  • SIAMMembershipStage
  • Product
  • Component
  • FullVersion

func RunWithPgLock

func RunWithPgLock(ctx context.Context, db *pgxpool.Pool, name string, fn func(ctx context.Context)) func() error

RunWithPgLock returns a function that executes the provided function within a PostgreSQL advisory lock. The lock is identified by a hash of the given name,ensuring that only one instance of the function can run concurrently across different processes or threads that use the same lock name. If the lock cannot be acquired, the function will log a message and return without executing the provided function.

Types

type DeploymentStage

type DeploymentStage string

DeploymentStage is the type that defines deployments stages in ODJ

const (
	StageTest  DeploymentStage = "test"
	StageDev   DeploymentStage = "dev"
	StageQA    DeploymentStage = "qa"
	StageProd  DeploymentStage = "prod"
	StageLocal DeploymentStage = ""
)
var Stage DeploymentStage

Stage is the current deployment stage, determined by the ODJ_EE_STAGE environment variable. It defaults to "local" if not set or empty.

func (DeploymentStage) String

func (s DeploymentStage) String() string

String returns the string representation of the deployment stage, with "local" as the default for empty stages.

type SIAMGroupMembershipsDTO

type SIAMGroupMembershipsDTO []string

SIAMGroupMembershipsDTO is a custom type for unmarshaling group memberships from SIAM JWTs.

func (*SIAMGroupMembershipsDTO) UnmarshalJSON

func (dto *SIAMGroupMembershipsDTO) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an array of strings into a slice of strings but if the input is a single string it will be converted to a slice with one element. This fixes the inconsistency in the SIAM JWT format.

Jump to

Keyboard shortcuts

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