Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The timezone middleware detects user timezone from headers, cookies, or client hints for proper time display. Use it when you need:
  • Time localization
  • Timezone-aware scheduling
  • User time preferences

Installation

import "github.com/go-mizu/mizu/middlewares/timezone"

Quick Start

app := mizu.New()

app.Use(timezone.New())

app.Get("/time", func(c *mizu.Ctx) error {
    tz := timezone.Get(c)
    loc, _ := time.LoadLocation(tz)
    now := time.Now().In(loc)
    return c.JSON(200, map[string]string{
        "timezone": tz,
        "time":     now.Format(time.RFC3339),
    })
})

Configuration

Options

OptionTypeDefaultDescription
Defaultstring"UTC"Default timezone
Headerstring"X-Timezone"Timezone header
CookieNamestring"tz"Cookie name

Examples

Basic Detection

app.Use(timezone.New())

Custom Header

app.Use(timezone.New(timezone.Options{
    Header: "X-User-Timezone",
}))

With Default

app.Use(timezone.New(timezone.Options{
    Default: "America/New_York",
}))

Client-Side Detection

// Set timezone cookie
document.cookie = `tz=${Intl.DateTimeFormat().resolvedOptions().timeZone}`;
app.Use(timezone.New(timezone.Options{
    CookieName: "tz",
}))

API Reference

Functions

// New creates timezone middleware
func New(opts ...Options) mizu.Middleware

// Get returns detected timezone
func Get(c *mizu.Ctx) string

// Location returns time.Location
func Location(c *mizu.Ctx) *time.Location

Common Timezones

TimezoneDescription
UTCCoordinated Universal Time
America/New_YorkEastern Time
Europe/LondonUK Time
Asia/TokyoJapan Time

Technical Details

Implementation

The timezone middleware uses a multi-source detection strategy to identify the user’s timezone:
  1. Context Storage: Timezone information is stored in the request context using a type-safe context key
  2. Info Structure: Contains three key pieces of information:
    • Name: IANA timezone identifier (e.g., “America/New_York”)
    • Location: Parsed time.Location object for time conversions
    • Offset: UTC offset in seconds for the current time
  3. Lookup Order: Configurable detection precedence via the Lookup option (default: “header,cookie,query”)
  4. Validation: Invalid timezone names automatically fall back to the configured default
  5. Cookie Management: Optional automatic cookie setting with configurable max age (default: 30 days)

Detection Flow

Request → Check Header → Check Cookie → Check Query → Default → Load Location → Store in Context

Helper Functions

The middleware provides several convenience functions:
  • Get(c): Returns complete timezone info
  • Location(c): Returns time.Location for time operations
  • Name(c): Returns timezone name string
  • Offset(c): Returns UTC offset in seconds
  • Now(c): Returns current time in detected timezone

Convenience Constructors

  • FromHeader(header): Only check specific header
  • FromCookie(name): Only check specific cookie
  • WithDefault(tz): Set custom default timezone

Best Practices

  • Default to UTC for storage
  • Convert to user timezone for display
  • Use IANA timezone names
  • Detect via JavaScript for accuracy

Testing

The middleware includes comprehensive test coverage for all functionality:
Test CaseDescriptionExpected Behavior
TestNewDefault middleware creationReturns UTC timezone when no timezone is detected
TestWithOptions_FromHeaderTimezone detection from headerReads timezone from X-Timezone header (America/New_York)
TestWithOptions_FromCookieTimezone detection from cookieReads timezone from cookie named “timezone” (Europe/London)
TestWithOptions_FromQueryTimezone detection from query parameterReads timezone from “tz” query parameter (Asia/Tokyo)
TestWithOptions_SetCookieCookie setting functionalityAutomatically sets timezone cookie when SetCookie=true
TestWithOptions_InvalidTimezoneInvalid timezone handlingFalls back to UTC default when invalid timezone provided
TestWithOptions_CustomDefaultCustom default timezoneUses America/Los_Angeles as default instead of UTC
TestLocationLocation helper functionReturns correct time.Location object (Europe/Paris)
TestNameName helper functionReturns timezone name string (Australia/Sydney)
TestOffsetOffset helper functionReturns correct UTC offset in seconds (0 for UTC)
TestNowNow helper functionReturns current time in detected timezone location
TestFromHeaderFromHeader constructorCreates middleware that only reads from custom header (X-User-Tz)
TestFromCookieFromCookie constructorCreates middleware that only reads from custom cookie (user_tz)
TestWithDefaultWithDefault constructorCreates middleware with custom default (Asia/Singapore)
TestLookupPrecedenceLookup order precedenceHeader takes precedence over cookie and query when all are present