Penguin

module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0

README

Penguin Library Documentation

This library focuses on routes, where each route is configured individually and in detail, allowing for precise control over HTTP handling.

Table of Contents


Router Package

The router package provides an HTTP router for Go applications, allowing you to register routes and handle HTTP requests.

Router Table of Contents
Functions
InitRouter()

Returns the router instance.

router := router.InitRouter()
NewRoute(route Route)

Registers a new route with a specific path, HTTP method, and handler function. You can also specify additional methods for the same path.

Parameters:

  • route: A Route struct containing:
    • Path: The URL path (string).
    • Method: The primary HTTP method (HTTPMethod).
    • Handler: The function to handle the request (HandleFunc).
    • AditionalMethods: Optional additional HTTP methods for the same path ([]HTTPMethod).

Example:

route := router.Route{
    Path:    "/api/users",
    Method:  router.GET,
    Handler: func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Users list"))
    },
}
router.NewRoute(route)

With additional methods:

route := router.Route{
    Path:             "/api/users",
    Method:           router.POST,
    Handler:          userHandler,
    AditionalMethods: []router.HTTPMethod{router.PUT, router.DELETE},
}
router.NewRoute(route)
StartServer(s string)

Starts the HTTP server on the specified address.

Parameters:

  • s: The server address (e.g., ":8080").

The server is started with read/write/idle timeouts and a header size limit (router.DefaultServerConfig). Override them with SetServerConfig before starting, and stop gracefully with Shutdown(ctx).

Example:

r := router.InitRouter() // or router.NewRouter() for an independent instance
r.SetServerConfig(router.DefaultServerConfig)
go r.StartServer(":8080")
defer r.Shutdown(context.Background())

Routes can be registered at any time, including after the server has started. HEAD falls back to the GET handler, and an unregistered OPTIONS returns 204 with an Allow header. Route.Path must not contain a method prefix such as "GET /x".

Set Route.CORS to apply a CORS config: the handler is wrapped with middlewares.WithCors, and the router answers CORS preflights for the path (with Access-Control-Allow-Methods) without running any handler. All routes on one path must share the same config.

config := cors.NewCORSConfig(cors.WithAllowedOrigins([]string{"https://app.example"}))
r.NewRoute(router.Route{Path: "/api/items", Method: router.POST, Handler: createItem, CORS: config})
HTTP Methods

Supported HTTP methods:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • OPTIONS
  • HEAD

Auth Package

The auth package provides JWT-based authentication, supporting plain JWT and JWT with RBAC.

Functions
LoadPrivateKeyFromPEM(keyPem []byte) (*ecdsa.PrivateKey, error)

Loads an ECDSA private key from PEM bytes, in SEC1 (EC PRIVATE KEY) or PKCS#8 (PRIVATE KEY) format. LoadPrivateKeyFromFile is kept as a deprecated alias.

Example:

keyPem := []byte("-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----")
privateKey, err := auth.LoadPrivateKeyFromPEM(keyPem)

Both auth types are safe for concurrent use and keep no per-request state. Every request gets a fresh claims value. Tokens must carry exp, and only the ES* algorithm that matches the key's curve is accepted. Use NewJwtAuthWithPublicKey / NewJwtAuthWithRbacAndPublicKey for services that only verify tokens, and WithIssuer / WithAudience (or JwtAuthRbacWithIssuer / JwtAuthRbacWithAudience) to enforce iss and aud.

The auth middlewares store the user under auth.UserContextKey, a typed key no other package can collide with. The plain string key "user" (auth.DefaultContextKey) is deprecated; pass auth.WithCustomContextKey(auth.DefaultContextKey) to keep using it.

NewJwtAuth(secret *ecdsa.PrivateKey, claimsType plainClaimsInterface) *JwtAuth

Creates a JWT auth instance.

Example:

jwtAuth := auth.NewJwtAuth(privateKey, &auth.PlainClaims{})
NewJwtAuthWithRbac(secret *ecdsa.PrivateKey, claimsType rBACClaimsInterface) *RBACJwtAuth

Creates a JWT auth instance with RBAC.

Example:


rbacAuth := auth.NewJwtAuthWithRbac(privateKey, &auth.RBACClaims{})
Creating Claims
PlainClaims

To create a PlainClaims instance:

claims := &auth.PlainClaims{
    RegisteredClaims: jwt.RegisteredClaims{
        Issuer:    "your-issuer",
        Subject:   "user-id",
        ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
        IssuedAt:  jwt.NewNumericDate(time.Now()),
    },
}
RBACClaims

To create a RBACClaims instance with roles:

claims := &auth.RBACClaims{
    RegisteredClaims: jwt.RegisteredClaims{
        Issuer:    "your-issuer",
        Subject:   "user-id",
        ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
        IssuedAt:  jwt.NewNumericDate(time.Now()),
    },
    Roles: []string{"admin", "user"},
}

CORS Package

The cors package allows you to create CORS configurations for your routes.

Functions
NewCORSConfig(options ...func(*CORSConfig)) *CORSConfig

Creates a new CORS configuration.

Example:

config := cors.NewCORSConfig(
    cors.WithAllowedOrigins([]string{"http://localhost:3000"}),
    cors.WithAllowedHeaders([]string{"Content-Type", "Authorization"}),
)

NewCORSConfig panics if AllowAllOrigin (*) is combined with WithAllowCredentials(true). Browsers reject that combination, so list the allowed origins explicitly. Responses that echo an origin carry Vary: Origin, and preflights from disallowed origins get 403 with no CORS headers.

WithAllowedOrigins(origins []string) func(*CORSConfig)

Sets allowed origins.

WithAllowedHeaders(headers []string) func(*CORSConfig)

Sets allowed headers.

WithExposedHeaders(headers []string) func(*CORSConfig)

Sets exposed headers.

WithAllowCredentials(allow bool) func(*CORSConfig)

Sets allow credentials.

WithMaxAge(age int) func(*CORSConfig)

Sets max age for preflight.

WithOptionsPassthrough(passthrough bool) func(*CORSConfig)

Sets options passthrough.


Middlewares Package

The middlewares package provides abstract middlewares for common HTTP functionalities. For WithAuthMiddleware and WithCors, you need to use the configurations from the auth and cors packages respectively.

Functions
WithAuthMiddleware(auth auth.PlainAuthInterface, hf handleFunc, opts ...authMiddlewareOption) handleFunc

Applies plain JWT authentication.

Example:

handler := middlewares.WithAuthMiddleware(jwtAuth, func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Authenticated"))
}, middlewares.WithTimeout(5*time.Second))

The timeout option is optional. Without it, the middleware inherits the incoming request context without adding a deadline.

Passing a nil auth panics at construction, so authentication can never be silently skipped.

WithAuthAndRBAC(authType auth.RBACAuthInterface, roles []string, hf handleFunc, opts ...authMiddlewareOption) handleFunc

Applies JWT authentication with RBAC. The role check runs against the user returned by GetUser for the same request. Custom implementations of RBACAuthInterface must implement RBAC(user any, allowedRoles []string) bool.

Example:

handler := middlewares.WithAuthAndRBAC(rbacAuth, []string{"admin"}, func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Authorized"))
}, middlewares.WithTimeout(5*time.Second))
WithTimeout(timeout time.Duration) authMiddlewareOption

Adds a deadline to the authentication middleware context. The deadline covers authentication and the downstream handler. The timeout must be greater than zero. Context cancellation is cooperative and does not automatically return an HTTP timeout response.

WithCors(corrsConfig *cors.CORSConfig, hf handleFunc) handleFunc

Applies CORS configuration.

Example:

config := cors.NewCORSConfig(cors.WithAllowedOrigins([]string{"*"}))
handler := middlewares.WithCors(config, func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("CORS enabled"))
})

Requests whose Origin is the request's own host are passed through without CORS headers. Other origins that are not allowed get 403. WithCors only sees preflights when the route registers OPTIONS; prefer Route.CORS, which handles them for you.

WithLogging(hf handleFunc) handleFunc

Logs HTTP requests. Use WithLoggingTrustedProxies(proxies, hf) to log the forwarded client IP from trusted proxies, or WithLoggingTrustedProxyHeader(proxies, header, hf) to read only X-Forwarded-For or only X-Real-IP. Naming the header is recommended: when both are read, a proxy that sets only X-Real-IP but forwards a client's X-Forwarded-For lets clients choose their IP.

The logging and recovery wrappers implement http.Flusher and http.Hijacker, so SSE and WebSocket handlers work behind them.

Example:

handler := middlewares.WithLogging(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Logged"))
})
WithRecovery(hf handleFunc) handleFunc

Recovers from panics.

Example:

handler := middlewares.WithRecovery(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Safe"))
})
WithRateLimiting(hf handleFunc, opts ...bucketOption) handleFunc

Limits request rate.

Example:

handler := middlewares.WithRateLimiting(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Limited"))
}, middlewares.RateLimitOptStartingLimit(10), middlewares.RateLimitOptLimitPerSecond(2.0))

Clients are keyed by IP and route; IPv6 clients are grouped by /64 (RateLimitOptIPv6PrefixLength). At most RateLimitOptMaxEntries clients (default 100,000) are tracked; when full, the least recently seen client is forgotten instead of rejecting new ones. RateLimitOptTrustedProxies and RateLimitOptTrustedProxyHeader control which forwarding header is honoured.

WithQueryParametersObligation(queryParameters []string, hf handleFunc) handleFunc

Requires query parameters.

Example:

handler := middlewares.WithQueryParametersObligation([]string{"id"}, func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Params checked"))
})
WithFeatureEnable(env string, hf handleFunc) handleFunc

Enables feature based on env var. The feature name must be set as an environment variable on the machine.

Example:

// Set env var: export ENABLE_FEATURE=true
handler := middlewares.WithFeatureEnable("ENABLE_FEATURE", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Feature enabled"))
})
WithFeatureEnabledByHeader(header string, hf handleFunc) handleFunc

Enables feature based on header. The header must be present in the request.

Example:

// Include header: X-Feature: true
handler := middlewares.WithFeatureEnabledByHeader("X-Feature", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Header enabled"))
})

Helpers Package

The helpers package provides utility functions for common HTTP operations.

Cache

All caches check expiry on every read. Re-storing a key resets its TTL, and an expiration <= 0 means the entry never expires. Each keyed cache (NewStringCache, NewUUIDCache, NewCleanerCacheInstance) runs a sweeper that drops expired entries every minute, so call Close() when you are done with it. A closed cache ignores writes, and Get*CacheInstance / NewCleanerCacheInstance return a fresh cache after a close. Get*CacheInstance registries are keyed by both name and value type. Get sends Cache-Control: private and Vary: Accept, Accept-Language, Authorization, Cookie on hits and misses, and GenerateCacheKey includes the host and hashes the Authorization and Cookie headers.

NewCacheItem(value any, expiration time.Duration) CacheItem

Creates a cache item.

Example:

item := helpers.NewCacheItem(data, time.Hour)
NewCleanerCacheInstance() *cleanerCache

Gets singleton cache instance. It holds at most helpers.DefaultResponseCacheMaxEntries (10,000) entries; while full, new keys are not stored. Change the cap with cache.SetMaxEntries(n) (<= 0 removes it).

Example:

cache := helpers.NewCleanerCacheInstance()
Set(key string, i CacheItem)

Stores item in cache with expiration.

Example:

cache.Set("key", item)
Get(w http.ResponseWriter, key string) (CacheItem, bool)

Retrieves item from cache, sets HTTP headers.

Example:

item, found := cache.Get(w, "key")
GenerateCacheKey(r *http.Request) string

Generates cache key from request.

Example:

key := helpers.GenerateCacheKey(r)
Body
DeserializeBodyWithLimit(r *http.Request, dto any, maxBytes int64) error

Deserializes JSON body with size limit.

Example:

var user User
err := helpers.DeserializeBodyWithLimit(r, &user, 1024)
Request
Context
GetContextValue[T any](r *http.Request, key any) (T, error)

Gets typed value from request context. key can be a string or a custom key type.

Example:

claims, err := helpers.GetContextValue[*auth.RBACClaims](r, auth.UserContextKey)
Pagination
GetPaginationParams(r *http.Request, defaultPageSize uint) PaginationParams

Gets pagination params from query. page is at least 1, and pageSize is capped at helpers.DefaultMaxPageSize (or defaultPageSize if that is larger). Use GetPaginationParamsWithMax for a custom cap, GetPaginationParamsWithLimits to also clamp page (bounding the SQL offset), and params.Offset() for the SQL offset.

Example:

params := helpers.GetPaginationParams(r, 10)
Path Values
GetUintPathValue(identifier string, r *http.Request) (uint64, error)

Gets uint from path value.

Example:

id, err := helpers.GetUintPathValue("id", r)
GetUUidPathValue(identifier string, r *http.Request) (uuid.UUID, error)

Gets UUID from path value.

Example:

id, err := helpers.GetUUidPathValue("uuid", r)
GetStringPathValue(identifier string, r *http.Request, options ...MaxStringLengthOption) (string, error)

Gets a trimmed string from a path value, limited to the given number of characters (runes). The value is not modified: use parameterised queries and output encoding rather than relying on input stripping.

Example:

name, err := helpers.GetStringPathValue("name", r)
WithCustomLengthOption(length int) MaxStringLengthOption

Sets custom max length for string.

Example:

name, err := helpers.GetStringPathValue("name", r, helpers.WithCustomLengthOption(100))
GetNullNaiveDateTimePathValue(identifier string, r *http.Request) (NullNaiveDateTime, error)

Gets nullable naive datetime from path value without a timezone, using values like "2006-01-02T15:04:05" or "2006-01-02T15:04:05.000".

Example:

createdAt, err := helpers.GetNullNaiveDateTimePathValue("createdAt", r)
Query Params
GetNullUint64QueryParam(queryParameter string, r *http.Request) (sql.NullInt64, error)

Gets nullable uint64 from query.

Example:

val, err := helpers.GetNullUint64QueryParam("limit", r)
GetNullInt64QueryParam(queryParameter string, r *http.Request) (sql.NullInt64, error)

Gets nullable int64 from query.

Example:

val, err := helpers.GetNullInt64QueryParam("offset", r)
GetNullBoolQueryParam(queryParameter string, r *http.Request) (sql.NullBool, error)

Gets nullable bool from query.

Example:

val, err := helpers.GetNullBoolQueryParam("active", r)
GetNullUUIDQueryParam(queryParameter string, r *http.Request) (uuid.NullUUID, error)

Gets nullable UUID from query.

Example:

val, err := helpers.GetNullUUIDQueryParam("userId", r)
GetNullTimeQueryParam(queryParameter string, r *http.Request) (sql.NullTime, error)

Gets nullable time from query.

Example:

val, err := helpers.GetNullTimeQueryParam("createdAt", r)
GetNullNaiveDateTimeQueryParam(queryParameter string, r *http.Request) (NullNaiveDateTime, error)

Gets nullable naive datetime from query without a timezone, using values like "2006-01-02T15:04:05" or "2006-01-02T15:04:05.000".

Example:

val, err := helpers.GetNullNaiveDateTimeQueryParam("createdAt", r)
GetNullStringQueryParam(queryParameter string, r *http.Request) (sql.NullString, error)

Gets nullable string from query.

Example:

val, err := helpers.GetNullStringQueryParam("search", r)
Response
SendSuccessResponse(w http.ResponseWriter, data any)

Sends JSON success response.

Example:

helpers.SendSuccessResponse(w, data)
SendValidationErrorResponse(w http.ResponseWriter, errors []string)

Sends validation errors.

Example:

helpers.SendValidationErrorResponse(w, []string{"Invalid input"})
SendErrorResponse(w http.ResponseWriter, statusCode int, message string)

Sends error response.

Example:

helpers.SendErrorResponse(w, 500, "Internal error")
SendNoContentResponse(w http.ResponseWriter)

Sends 204 No Content.

Example:

helpers.SendNoContentResponse(w)
Tokens
GenerateJwtToken(claims jwt.Claims, secret *ecdsa.PrivateKey) (string, error)

Generates JWT token signed with the ES* method matching the key's curve (P-256 → ES256, P-384 → ES384, P-521 → ES512). Set ExpiresAt: tokens without exp are rejected by the auth types.

Example:

token, err := helpers.GenerateJwtToken(claims, privateKey)

This documentation provides an overview of the Penguin library packages. For more details, refer to the source code.

Types Package

The types package (part of the router package) provides custom types for handling dates and times in JSON serialization.

Types
Date

Represents a date with year, month, and day.

Fields:

  • Year int
  • Month int
  • Day int

Methods:

  • ToString() string: Converts to string format "2006-01-02" (makes it stringeable).
  • Marshal() ([]byte, error): Marshals to JSON (makes it JSON compatible).
  • Unmarshal(data []byte) error: Unmarshals from JSON (makes it JSON compatible).
TimeStamp

Represents a timestamp with date, time, and timezone.

Fields:

  • Year int
  • Month int
  • Day int
  • Hour int
  • Minute int
  • Second int
  • Microsecond int
  • Timezone string

Methods:

  • ToString() string: Converts to string format "2006-01-02 15:04:05.000000-07" (makes it stringeable).
  • Marshal() ([]byte, error): Marshals to JSON (makes it JSON compatible).
  • Unmarshal(data []byte) error: Unmarshals from JSON (makes it JSON compatible).
Time

Represents a time with hour, minute, second, and millisecond.

Fields:

  • Hour int
  • Minute int
  • Second int
  • Milisecond int

Methods:

  • ToString() string: Converts to string format "15:04:05.000" (makes it stringeable).
  • Marshal() ([]byte, error): Marshals to JSON (makes it JSON compatible).
  • Unmarshal(data []byte) error: Unmarshals from JSON (makes it JSON compatible).

Logger Package

The logger package provides logging functionality with file and console loggers.

Functions
GetFileLogger() *FileLogger

Gets the singleton file logger instance.

GetConsoleLogger() *ConsoleLogger

Gets the singleton console logger instance. Lines are written to stdout by a background goroutine, so a slow stdout never blocks callers; when more than 4,096 lines are waiting, new ones are dropped and a count is logged. Call Flush() before exiting to write pending lines (Fatal does this).

FileLogger Methods
Configuration Methods
Configure(logDir string, baseFileName string, maxFileSizeMB int, maxAgeDays int)

Configures the file logger.

SetLevel(level LogLevel)

Sets the log level.

Logging Methods
Debug(msg string, args ...any)

Logs a debug message.

Info(msg string, args ...any)

Logs an info message.

Warn(msg string, args ...any)

Logs a warning message.

Error(msg string, args ...any)

Logs an error message.

Fatal(msg string, args ...any)

Logs a fatal message and exits.

ConsoleLogger Methods
Configuration Methods
SetLevel(level LogLevel)

Sets the log level.

EnableColors(enabled bool)

Enables or disables colored output.

Logging Methods
Debug(msg string, args ...any)

Logs a debug message to console.

Info(msg string, args ...any)

Logs an info message to console.

Warn(msg string, args ...any)

Logs a warning message to console.

Error(msg string, args ...any)

Logs an error message to console.

Fatal(msg string, args ...any)

Logs a fatal message to console and exits.

Types
  • LogLevel: Enum for log levels (DEBUG, INFO, WARN, ERROR, FATAL).
  • Logger: Interface for loggers.

Scheduler Package

The scheduler package provides asynchronous job scheduling using a timer + priority queue strategy (no fixed 1-second polling loop).

Functions
StartScheduler() *Scheduler

Starts the shared singleton scheduler instance. Stopping it affects every user of the singleton.

NewScheduler() *Scheduler

Starts an independent scheduler owned by the caller.

JobFunction(f JobFuncInterface) *jobFunction

Creates a job function. A job function can be scheduled only once, so create a new one per job. Panics inside Execute are recovered and logged, and removing or stopping a job while it runs is safe.

Scheduler Methods
Configuration and Usage Methods
ScheduleOneTimeJob(delay time.Duration, jobFunction *jobFunction) (uint64, error)

Schedules a one-time job after a delay. The first run is never immediate: delay must be greater than zero.

Example:

id, err := sched.ScheduleOneTimeJob(5*time.Second, scheduler.JobFunction(myJob))
ScheduleIntervalJob(interval time.Duration, jobFunction *jobFunction) (uint64, error)

Schedules a recurring interval job. The first run is never immediate: first execution is after interval.

Example:

id, err := sched.ScheduleIntervalJob(20*time.Minute, scheduler.JobFunction(myJob))
ScheduleProgrammedOneTimeJob(when time.Time, jobFunction *jobFunction) (uint64, error)

Schedules a one-time job at an exact future timestamp. when must be strictly in the future.

Example:

id, err := sched.ScheduleProgrammedOneTimeJob(time.Now().Add(2*time.Hour), scheduler.JobFunction(myJob))
ScheduleProgrammedIntervalJob(everyXDays int, at time.Time, jobFunction *jobFunction) (uint64, error)

Schedules a recurring job every everyXDays days at the clock-time extracted from at, in at's location (so time.UTC means UTC whatever the server zone is). The wall-clock time is kept across DST changes. If today's target time has already passed, first run is moved to the next valid day window.

Example:

at := time.Date(2000, 1, 1, 8, 30, 0, 0, time.Local)
id, err := sched.ScheduleProgrammedIntervalJob(1, at, scheduler.JobFunction(myJob))
RemoveJob(id uint64) error

Removes a job.

PauseJob(id uint64) error

Pauses a job.

UnPauseJob(id uint64) error

Unpauses a job.

GetChannel(id uint64) chan []any

Gets the return channel for a job.

Stop()

Stops the scheduler.

IsRunning() bool

Checks if the scheduler is running.

Pause()

Pauses the scheduler.

UnPause()

Unpauses the scheduler.

jobFunction Methods
WithReturnChannel() (*jobFunction, chan []any)

Adds a return channel to the job function.

Types
  • JobFuncInterface: Interface for job functions.

License

Penguin is licensed under the Apache License 2.0.

Directories

Path Synopsis
internal/clientip
Package clientip resolves the client address of a request without trusting forwarding headers from arbitrary peers.
Package clientip resolves the client address of a request without trusting forwarding headers from arbitrary peers.

Jump to

Keyboard shortcuts

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