cb

package module
v0.0.0-...-b444eb5 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2022 License: MIT Imports: 2 Imported by: 0

README ¶

gp-cb

go-cb is just a library to help you to use the sony/gobreaker without need deal with type conversions thus making your code safer.

Example

Using gobreaker your code would look like:

var circuitbreaker *breaker.CircuitBreaker

func Get(url string) ([]byte, error) {
	body, err := circuitbreaker.Execute(func() (interface{}, error) {
		resp, err := http.Get(url)
		if err != nil {
			return nil, err
		}

		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}

		return body, nil
	})
	if err != nil {
		return nil, err
	}

	return body.([]byte), nil
}

Using this library:

var circuitbreaker *breaker.CircuitBreaker

func Get(url string) ([]byte, error) {
	body, err := cb.Execute(circuitbreaker, func() ([]byte, error) {
		resp, err := http.Get(url)
		if err != nil {
			return nil, err
		}

		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}

		return body, nil
	})
	if err != nil {
		return nil, err
	}
	return body, nil
}

But ... WHY!?!? 😫😫😫

Well, it didn't reduced that much my code, why should I bother?

Yes, you are totally right. Using this light wrapper won't shorten your code enough to justify its usage. However, it will give you more safety since it will ensure you will always return the same type you are expecting. Since on the original implementation uses interface{} you can easily return a type that is not the one you are expecting. Usually it happens when you should be returning a pointer instead of a value, or vice-versa.

License

MIT

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

View Source
var (
	ErrInvalidConversion = errors.New("invalid conversion")
)

Functions ¶

func Execute ¶

func Execute[T any](cb *gobreaker.CircuitBreaker, f func() (T, error)) (r T, rerr error)

Execute executes the given function and returns the result using generics so no conversion need to be handled by the caller.

Types ¶

This section is empty.

Jump to

Keyboard shortcuts

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