ctxutils

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2025 License: MIT Imports: 3 Imported by: 0

README

CI PkgGoDev

ctxutils

ctxutils provides some utilities related to context package.

Install

go get github.com/aereal/ctxutils

License

See LICENSE file.

Documentation

Overview

Package ctxutils provides some utilities related to context package.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextWithNarrowedDeadline

func ContextWithNarrowedDeadline(ctx context.Context, grace time.Duration) (context.Context, func())

ContextWithNarrowedDeadline returns a new context with a shortened deadline applying a grace period reduction.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/aereal/ctxutils"
	internaltime "github.com/aereal/ctxutils/internal/time"
)

func main() {
	base, err := time.ParseInLocation(time.DateTime, "2006-01-02 15:04:05", time.UTC)
	if err != nil {
		panic(err)
	}
	internaltime.SetNow(base)

	originalDeadline := base.Add(time.Hour * 1)
	ctx, _ := context.WithDeadline(context.Background(), originalDeadline) //nolint:govet
	narrowedCtx, _ := ctxutils.ContextWithNarrowedDeadline(ctx, time.Minute*4+time.Second*5)
	narrowedDeadline, ok := narrowedCtx.Deadline()
	if !ok {
		panic("deadline is not narrowed")
	}
	fmt.Printf("original deadline: %s\n", originalDeadline.In(time.UTC).Format(time.DateTime))
	fmt.Printf("new deadline: %s\n", narrowedDeadline.In(time.UTC).Format(time.DateTime))
}
Output:

original deadline: 2006-01-02 16:04:05
new deadline: 2006-01-02 16:00:00

func ContextWithNarrowedDeadlineCause

func ContextWithNarrowedDeadlineCause(ctx context.Context, grace time.Duration, cause error) (context.Context, func())

ContextWithNarrowedDeadlineCause returns a new context with a shortened deadline and an associated cause error, applying a grace period reduction.

Types

This section is empty.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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