eddieowens / opts

Small Go lib for generic, vararg func opts

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

opts

Go Report Card License godoc

Generic varargs options for your funcs

Install

go get github.com/eddieowens/opts

Why

It's very common within several libraries to use vararg options e.g. in the popular grpc library

grpc.Dial(":8080", grpc.WithBlock())

This provides a flexible and backwards compatible way to configure your APIs. The only problem is that it often requires a good deal of boilerplate. This library aims to help with reducing the boilerplate.

Example

package main

import (
	"github.com/eddieowens/opts"
	"time"
)

type GetUserOpts struct {
	// Timeout if it takes longer than the specified time to get the user
	Timeout time.Duration
}

// Implement (optional) opts.OptionsDefaulter interface to provide sane defaults.
func (g GetUserOpts) DefaultOptions() GetUserOpts {
	return GetUserOpts{Timeout: 5 * time.Second}
}

// Create option mutator func
func WithTimeout(t time.Duration) opts.Opt[GetUserOpts] {
	return func(o *GetUserOpts) {
		o.Timeout = t
	}
}

// Apply the options
func GetUser(userId string, op ...opts.Opt[GetUserOpts]) (*User, error) {
	o := opts.DefaultApply(op...)
	...
}

About

Small Go lib for generic, vararg func opts

License:MIT License


Languages

Language:Go 100.0%