scattergather

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2022 License: MIT Imports: 4 Imported by: 0

README

scatter-gather

Build codecov

A simple implementation of scatter gather pattern in Go.

Usage

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"

	scattergather "github.com/tuyentv96/scatter-gather"
)

func main() {
	urls := []string{
		"https://jsonplaceholder.typicode.com/todos/1",
		"https://jsonplaceholder.typicode.com/todos/2",
		"https://jsonplaceholder.typicode.com/todos/3",
		"https://jsonplaceholder.typicode.com/todos/4",
		"https://jsonplaceholder.typicode.com/todos/5",
		"https://jsonplaceholder.typicode.com/todos/6",
		"https://jsonplaceholder.typicode.com/todos/7",
		"https://jsonplaceholder.typicode.com/todos/8",
		"https://jsonplaceholder.typicode.com/todos/9",
	}

	batchSize := 4
	result, err := scattergather.ScattergatherWithInputParams(urls, batchSize, func(params []string) ([]string, error) {
		rs := make([]string, 0, len(params))
		for _, url := range params {
			fmt.Printf("Fetching url: %s\n", url)
			resp, err := http.Get(url)
			if err != nil {
				return nil, err
			}

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return nil, err
			}
			rs = append(rs, string(body))
			fmt.Printf("Finished url: %s\n", url)
		}

		return rs, nil
	})
	if err != nil {
		fmt.Printf("Err: %+v\n", err)
	}

	fmt.Printf("result size: %d\n", len(result))
}

License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidBatchSize = errors.New("batch size must be great than zero")
)

Functions

func ScattergatherWithFuncs added in v0.1.1

func ScattergatherWithFuncs[T any](futures [](func() ([]T, error))) ([]T, error)

ScattergatherWithFuncs executes multiple futures funtions Return error if anfuture has failed.

func ScattergatherWithInputParams

func ScattergatherWithInputParams[K, V any](params []K, batchSize int, fn func([]K) ([]V, error)) ([]V, error)

ScattergatherWithInputParams executes with input params array. Input params array will be partitioned by batchSize Each batch is executed by fn Return errors if any params is failed.

Types

This section is empty.

Jump to

Keyboard shortcuts

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