vendredi 29 juillet 2022

Go - Builder Pattern in Containerd

I am relativly new to Golang and learning about Containerd. While reading the docs; I came along some code:

containerd/client_opts.go

type clientOpts struct {
    defaultns       string
    defaultRuntime  string
    defaultPlatform platforms.MatchComparer
    services        *services
    dialOptions     []grpc.DialOption
    callOptions     []grpc.CallOption
    timeout         time.Duration
}

// ClientOpt allows callers to set options on the containerd client
type ClientOpt func(c *clientOpts) error

// WithDefaultNamespace sets the default namespace on the client
//
// Any operation that does not have a namespace set on the context will
// be provided the default namespace
func WithDefaultNamespace(ns string) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultns = ns
        return nil
    }
}

// WithDefaultRuntime sets the default runtime on the client
func WithDefaultRuntime(rt string) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultRuntime = rt
        return nil
    }
}

// WithDefaultPlatform sets the default platform matcher on the client
func WithDefaultPlatform(platform platforms.MatchComparer) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultPlatform = platform
        return nil
    }
}

// WithDialOpts allows grpc.DialOptions to be set on the connection
func WithDialOpts(opts []grpc.DialOption) ClientOpt {
    return func(c *clientOpts) error {
        c.dialOptions = opts
        return nil
    }
}

// WithCallOpts allows grpc.CallOptions to be set on the connection
func WithCallOpts(opts []grpc.CallOption) ClientOpt {
    return func(c *clientOpts) error {
        c.callOptions = opts
        return nil
    }

containerd/client.go

func New(address string, opts ...ClientOpt) (*Client, error) {
    var copts clientOpts
    for _, o := range opts {
        if err := o(&copts); err != nil {
            return nil, err
        }
    }
    ...

So I was wondering. Is there a name for this paradigm? passing var parameters that are functions and setting fields with a for a loop. This seems like a builder pattern but I'm just curious as to why it's done this way; the returning of functions from functions and the builder use, if that's what it is, in this nontraditional way.

Once again, new to Go so maybe this is idiomatic of Go.

Aucun commentaire:

Enregistrer un commentaire