singleflight

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 4 Imported by: 1

README

gopkg/singleflight

Go Report Card GoDoc OSCS Status

gopkg/singleflight is an helper for golang.org/x/sync/singleflight.

Install

go get github.com/wwwangxc/gopkg/singleflight

Quick Start

package main

import (
	"context"
	"time"

	"golang.org/x/sync/singleflight"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

    // the function for key `function_key` will expire in 1 minute. default 1 second
	ret, err := singleflight.Do(ctx, "function_key",
		func(ctx context.Context) (interface{}, error) {
			// dosomething...
			time.Sleep(2 * time.Second)
			return "Successfully", nil
		}, singleflight.WithExpiresIn(time.Minute))

    if err != nil {
        if singleflight.IsTimeout(err) {
            fmt.Println("timeout")
            return
        }

        return fmt.Println(err)
    }

    fmt.Println("OK")
}

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/wwwangxc/gopkg/singleflight"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	ret, err := singleflight.Do(ctx, "function_key",
		func(ctx context.Context) (interface{}, error) {
			// dosomething...
			time.Sleep(2 * time.Second)
			return "Successfully", nil
		}) // the function for key `function_key` will expire in 1 second

	switch {
	case err != nil:
		fmt.Println(err.Error())
	case ret != nil:
		fmt.Println(ret.(string))
	default:
	}

	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	ret, err = singleflight.Do(ctx, "function_key",
		func(ctx context.Context) (interface{}, error) {
			// dosomething...
			return "Successfully", nil
		}, singleflight.WithExpiresIn(time.Minute)) // the function for key `function_key` will expire in 1 minute

	switch {
	case err != nil:
		fmt.Println(err.Error())
	case ret != nil:
		fmt.Println(ret.(string))
	default:
	}

}
Output:

timeout
Successfully

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrTimeout timeout error
	ErrTimeout = errors.New("timeout")
)

Functions

func Do

func Do(ctx context.Context,
	key string, fn func(context.Context) (interface{}, error), opts ...Option) (interface{}, error)

Do helper for singleflight

For details, see: https://pkg.go.dev/golang.org/x/sync/singleflight

func IsTimeout

func IsTimeout(err error) bool

IsTimeout will return true when the error is timeout

Types

type Option

type Option func(*options)

Option of method do

func WithExpiresIn

func WithExpiresIn(expiresIn time.Duration) Option

WithExpiresIn set expiration time

Default `time.Second`

Jump to

Keyboard shortcuts

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