bharat nc
bharat nc

Reputation: 127

How to use type func(*dialOptions)

I am trying to use GoLang grpc library to make a dial. The GRPC.dial has a method signature like this:

func Dial(target string, opts ...DialOption) (*ClientConn, error)

and DialOption is a type like this:

    DialOptions func(*dialOptions)

dialOptions is itself a struct with other parameters but I want to pass userAgent string in transport.ConnectOptions which is another struct:

type dialOptions struct {
unaryInt    UnaryClientInterceptor
streamInt   StreamClientInterceptor
...
...
...

copts       transport.ConnectOptions
}


type ConnectOptions struct {
    // UserAgent is the application user agent.
    UserAgent string
...
...
}

How can I pass my user-agent in the along with the Dial function?

The library is linked here.

Upvotes: 0

Views: 588

Answers (1)

Iain Duncan
Iain Duncan

Reputation: 3394

This is an example of a functional option as outlined by Dave Cheney here:

https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

The essence is that you send in an optional function that modifies the ClientConn that is being created by the Dial function. The library comes with a bunch predefined including one to change the user-agent:

https://godoc.org/google.golang.org/grpc#WithUserAgent

So your code becomes:

dialWithUserAgent := grpc.Dial("target", grpc.WithUserAgent("user-agent"))

Upvotes: 1

Related Questions