dshakcsq64956 2018-03-09 04:20
浏览 292
已采纳

如何使用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.

  • 写回答

1条回答 默认 最新

  • dongya8378 2018-03-09 07:14
    关注

    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"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改